1
0
mirror of https://github.com/django/django.git synced 2025-03-12 18:30:48 +00:00

[5.2.x] Applied Black's 2025 stable style.

https://github.com/psf/black/releases/tag/25.1.0
Backport of ff3aaf036f0cb66cd8f404cd51c603e68aaa7676 from main
This commit is contained in:
Mariusz Felisiak 2025-03-01 19:41:37 +01:00
parent b8ceda4a51
commit 53bb1d5a24
46 changed files with 213 additions and 185 deletions

View File

@ -1,15 +1,15 @@
repos: repos:
- repo: https://github.com/psf/black-pre-commit-mirror - repo: https://github.com/psf/black-pre-commit-mirror
rev: 24.10.0 rev: 25.1.0
hooks: hooks:
- id: black - id: black
exclude: \.py-tpl$ exclude: \.py-tpl$
- repo: https://github.com/adamchainz/blacken-docs - repo: https://github.com/adamchainz/blacken-docs
rev: 1.19.0 rev: 1.19.1
hooks: hooks:
- id: blacken-docs - id: blacken-docs
additional_dependencies: additional_dependencies:
- black==24.10.0 - black==25.1.0
files: 'docs/.*\.txt$' files: 'docs/.*\.txt$'
args: ["--rst-literal-block"] args: ["--rst-literal-block"]
- repo: https://github.com/PyCQA/isort - repo: https://github.com/PyCQA/isort

View File

@ -14,6 +14,7 @@ from django.contrib.gis.db.backends.base.models import SpatialRefSysMixin
class OracleGeometryColumns(models.Model): class OracleGeometryColumns(models.Model):
"Maps to the Oracle USER_SDO_GEOM_METADATA table." "Maps to the Oracle USER_SDO_GEOM_METADATA table."
table_name = models.CharField(max_length=32) table_name = models.CharField(max_length=32)
column_name = models.CharField(max_length=1024) column_name = models.CharField(max_length=1024)
srid = models.IntegerField(primary_key=True) srid = models.IntegerField(primary_key=True)
@ -46,6 +47,7 @@ class OracleGeometryColumns(models.Model):
class OracleSpatialRefSys(models.Model, SpatialRefSysMixin): class OracleSpatialRefSys(models.Model, SpatialRefSysMixin):
"Maps to the Oracle MDSYS.CS_SRS table." "Maps to the Oracle MDSYS.CS_SRS table."
cs_name = models.CharField(max_length=68) cs_name = models.CharField(max_length=68)
srid = models.IntegerField(primary_key=True) srid = models.IntegerField(primary_key=True)
auth_srid = models.IntegerField() auth_srid = models.IntegerField()

View File

@ -50,6 +50,7 @@ from django.utils.encoding import force_bytes, force_str
# The OGR_DS_* routines are relevant here. # The OGR_DS_* routines are relevant here.
class DataSource(GDALBase): class DataSource(GDALBase):
"Wraps an OGR Data Source object." "Wraps an OGR Data Source object."
destructor = capi.destroy_ds destructor = capi.destroy_ds
def __init__(self, ds_input, ds_driver=False, write=False, encoding="utf-8"): def __init__(self, ds_input, ds_driver=False, write=False, encoding="utf-8"):

View File

@ -21,6 +21,7 @@ from django.contrib.gis.gdal.error import GDALException
# https://gdal.org/doxygen/ogr__core_8h_source.html # https://gdal.org/doxygen/ogr__core_8h_source.html
class OGREnvelope(Structure): class OGREnvelope(Structure):
"Represent the OGREnvelope C Structure." "Represent the OGREnvelope C Structure."
_fields_ = [ _fields_ = [
("MinX", c_double), ("MinX", c_double),
("MaxX", c_double), ("MaxX", c_double),

View File

@ -345,6 +345,7 @@ class SpatialReference(GDALBase):
class CoordTransform(GDALBase): class CoordTransform(GDALBase):
"The coordinate system transformation object." "The coordinate system transformation object."
destructor = capi.destroy_ct destructor = capi.destroy_ct
def __init__(self, source, target): def __init__(self, source, target):

View File

@ -1,3 +1,4 @@
class GEOSException(Exception): class GEOSException(Exception):
"The base GEOS exception, indicates a GEOS-related error." "The base GEOS exception, indicates a GEOS-related error."
pass pass

View File

@ -23,6 +23,7 @@ def check_cs_get(result, func, cargs):
# ## Coordinate sequence prototype factory classes. ## # ## Coordinate sequence prototype factory classes. ##
class CsInt(GEOSFuncFactory): class CsInt(GEOSFuncFactory):
"For coordinate sequence routines that return an integer." "For coordinate sequence routines that return an integer."
argtypes = [CS_PTR, POINTER(c_uint)] argtypes = [CS_PTR, POINTER(c_uint)]
restype = c_int restype = c_int
errcheck = staticmethod(check_cs_get) errcheck = staticmethod(check_cs_get)
@ -30,6 +31,7 @@ class CsInt(GEOSFuncFactory):
class CsOperation(GEOSFuncFactory): class CsOperation(GEOSFuncFactory):
"For coordinate sequence operations." "For coordinate sequence operations."
restype = c_int restype = c_int
def __init__(self, *args, ordinate=False, get=False, **kwargs): def __init__(self, *args, ordinate=False, get=False, **kwargs):

View File

@ -25,12 +25,14 @@ class geos_char_p(c_char_p):
# ### ctypes factory classes ### # ### ctypes factory classes ###
class GeomOutput(GEOSFuncFactory): class GeomOutput(GEOSFuncFactory):
"For GEOS routines that return a geometry." "For GEOS routines that return a geometry."
restype = GEOM_PTR restype = GEOM_PTR
errcheck = staticmethod(check_geom) errcheck = staticmethod(check_geom)
class IntFromGeom(GEOSFuncFactory): class IntFromGeom(GEOSFuncFactory):
"Argument is a geometry, return type is an integer." "Argument is a geometry, return type is an integer."
argtypes = [GEOM_PTR] argtypes = [GEOM_PTR]
restype = c_int restype = c_int
errcheck = staticmethod(check_minus_one) errcheck = staticmethod(check_minus_one)
@ -38,6 +40,7 @@ class IntFromGeom(GEOSFuncFactory):
class StringFromGeom(GEOSFuncFactory): class StringFromGeom(GEOSFuncFactory):
"Argument is a Geometry, return type is a string." "Argument is a Geometry, return type is a string."
argtypes = [GEOM_PTR] argtypes = [GEOM_PTR]
restype = geos_char_p restype = geos_char_p
errcheck = staticmethod(check_string) errcheck = staticmethod(check_string)

View File

@ -12,6 +12,7 @@ from django.contrib.gis.geos.prototypes.errcheck import check_predicate
# ## Binary & unary predicate factories ## # ## Binary & unary predicate factories ##
class UnaryPredicate(GEOSFuncFactory): class UnaryPredicate(GEOSFuncFactory):
"For GEOS unary predicate functions." "For GEOS unary predicate functions."
argtypes = [GEOM_PTR] argtypes = [GEOM_PTR]
restype = c_byte restype = c_byte
errcheck = staticmethod(check_predicate) errcheck = staticmethod(check_predicate)
@ -19,6 +20,7 @@ class UnaryPredicate(GEOSFuncFactory):
class BinaryPredicate(UnaryPredicate): class BinaryPredicate(UnaryPredicate):
"For GEOS binary predicate functions." "For GEOS binary predicate functions."
argtypes = [GEOM_PTR, GEOM_PTR] argtypes = [GEOM_PTR, GEOM_PTR]

View File

@ -16,6 +16,7 @@ from django.contrib.gis.geos.prototypes.geom import geos_char_p
class Topology(GEOSFuncFactory): class Topology(GEOSFuncFactory):
"For GEOS unary topology functions." "For GEOS unary topology functions."
argtypes = [GEOM_PTR] argtypes = [GEOM_PTR]
restype = GEOM_PTR restype = GEOM_PTR
errcheck = staticmethod(check_geom) errcheck = staticmethod(check_geom)

View File

@ -1,4 +1,5 @@
"Base Cache class." "Base Cache class."
import time import time
import warnings import warnings

View File

@ -1,4 +1,5 @@
"Database cache backend." "Database cache backend."
import base64 import base64
import pickle import pickle
from datetime import datetime, timezone from datetime import datetime, timezone

View File

@ -1,4 +1,5 @@
"File-based cache backend" "File-based cache backend"
import glob import glob
import os import os
import pickle import pickle

View File

@ -1,4 +1,5 @@
"Thread-safe in-memory cache backend." "Thread-safe in-memory cache backend."
import pickle import pickle
import time import time
from collections import OrderedDict from collections import OrderedDict

View File

@ -431,6 +431,7 @@ class BaseForm(RenderableFormMixin):
class Form(BaseForm, metaclass=DeclarativeFieldsMetaclass): class Form(BaseForm, metaclass=DeclarativeFieldsMetaclass):
"A collection of Fields, plus their associated data." "A collection of Fields, plus their associated data."
# This is a separate class from BaseForm in order to abstract the way # This is a separate class from BaseForm in order to abstract the way
# self.fields is specified. This class (Form) is the one that does the # self.fields is specified. This class (Form) is the one that does the
# fancy metaclass stuff purely for the semantic sugar -- it allows one # fancy metaclass stuff purely for the semantic sugar -- it allows one

View File

@ -7,6 +7,7 @@ _builtin_context_processors = ("django.template.context_processors.csrf",)
class ContextPopException(Exception): class ContextPopException(Exception):
"pop() has been called more times than push()" "pop() has been called more times than push()"
pass pass

View File

@ -546,6 +546,7 @@ class SuperVillain(Villain):
class FunkyTag(models.Model): class FunkyTag(models.Model):
"Because we all know there's only one real use case for GFKs." "Because we all know there's only one real use case for GFKs."
name = models.CharField(max_length=25) name = models.CharField(max_length=25)
content_type = models.ForeignKey(ContentType, models.CASCADE) content_type = models.ForeignKey(ContentType, models.CASCADE)
object_id = models.PositiveIntegerField() object_id = models.PositiveIntegerField()

View File

@ -7159,7 +7159,7 @@ class ReadonlyTest(AdminFieldExtractionMixin, TestCase):
url = reverse("admin:admin_views_pizza_change", args=(pizza.pk,)) url = reverse("admin:admin_views_pizza_change", args=(pizza.pk,))
with self.settings(LANGUAGE_CODE="fr"): with self.settings(LANGUAGE_CODE="fr"):
response = self.client.get(url) response = self.client.get(url)
self.assertContains(response, "<label>Toppings\u00A0:</label>", html=True) self.assertContains(response, "<label>Toppings\u00a0:</label>", html=True)
@override_settings(ROOT_URLCONF="admin_views.urls") @override_settings(ROOT_URLCONF="admin_views.urls")

View File

@ -350,10 +350,10 @@ class UsernameValidatorsTests(SimpleTestCase):
invalid_usernames = [ invalid_usernames = [
"o'connell", "o'connell",
"عبد ال", "عبد ال",
"zerowidth\u200Bspace", "zerowidth\u200bspace",
"nonbreaking\u00A0space", "nonbreaking\u00a0space",
"en\u2013dash", "en\u2013dash",
"trailingnewline\u000A", "trailingnewline\u000a",
] ]
v = validators.UnicodeUsernameValidator() v = validators.UnicodeUsernameValidator()
for valid in valid_usernames: for valid in valid_usernames:

View File

@ -90,7 +90,7 @@ class LastExecutedQueryTest(TestCase):
def test_query_encoding(self): def test_query_encoding(self):
"""last_executed_query() returns a string.""" """last_executed_query() returns a string."""
data = RawData.objects.filter(raw_data=b"\x00\x46 \xFE").extra( data = RawData.objects.filter(raw_data=b"\x00\x46 \xfe").extra(
select={"föö": 1} select={"föö": 1}
) )
sql, params = data.query.sql_with_params() sql, params = data.query.sql_with_params()

View File

@ -73,7 +73,7 @@ class FormsUtilsTestCase(SimpleTestCase):
) )
# Can take a Unicode string. # Can take a Unicode string.
self.assertHTMLEqual( self.assertHTMLEqual(
str(ErrorList(ValidationError("Not \u03C0.").messages)), str(ErrorList(ValidationError("Not \u03c0.").messages)),
'<ul class="errorlist"><li>Not π.</li></ul>', '<ul class="errorlist"><li>Not π.</li></ul>',
) )
# Can take a lazy string. # Can take a lazy string.
@ -107,7 +107,7 @@ class FormsUtilsTestCase(SimpleTestCase):
ValidationError( ValidationError(
[ [
"1. First error.", "1. First error.",
"2. Not \u03C0.", "2. Not \u03c0.",
gettext_lazy("3. Error."), gettext_lazy("3. Error."),
{ {
"error_1": "4. First dict error.", "error_1": "4. First dict error.",

View File

@ -15,17 +15,20 @@ class NamedModel(models.Model):
class SouthTexasCity(NamedModel): class SouthTexasCity(NamedModel):
"City model on projected coordinate system for South Texas." "City model on projected coordinate system for South Texas."
point = models.PointField(srid=32140) point = models.PointField(srid=32140)
radius = models.IntegerField(default=10000) radius = models.IntegerField(default=10000)
class SouthTexasCityFt(NamedModel): class SouthTexasCityFt(NamedModel):
"Same City model as above, but U.S. survey feet are the units." "Same City model as above, but U.S. survey feet are the units."
point = models.PointField(srid=2278) point = models.PointField(srid=2278)
class AustraliaCity(NamedModel): class AustraliaCity(NamedModel):
"City model for Australia, using WGS84." "City model for Australia, using WGS84."
point = models.PointField() point = models.PointField()
radius = models.IntegerField(default=10000) radius = models.IntegerField(default=10000)
allowed_distance = models.FloatField(default=0.5) allowed_distance = models.FloatField(default=0.5)
@ -34,19 +37,23 @@ class AustraliaCity(NamedModel):
class CensusZipcode(NamedModel): class CensusZipcode(NamedModel):
"Model for a few South Texas ZIP codes (in original Census NAD83)." "Model for a few South Texas ZIP codes (in original Census NAD83)."
poly = models.PolygonField(srid=4269) poly = models.PolygonField(srid=4269)
class SouthTexasZipcode(NamedModel): class SouthTexasZipcode(NamedModel):
"Model for a few South Texas ZIP codes." "Model for a few South Texas ZIP codes."
poly = models.PolygonField(srid=32140, null=gisfield_may_be_null) poly = models.PolygonField(srid=32140, null=gisfield_may_be_null)
class Interstate(NamedModel): class Interstate(NamedModel):
"Geodetic model for U.S. Interstates." "Geodetic model for U.S. Interstates."
path = models.LineStringField() path = models.LineStringField()
class SouthTexasInterstate(NamedModel): class SouthTexasInterstate(NamedModel):
"Projected model for South Texas Interstates." "Projected model for South Texas Interstates."
path = models.LineStringField(srid=32140) path = models.LineStringField(srid=32140)

View File

@ -6,7 +6,7 @@ from .models import DataModel
class BinaryFieldTests(TestCase): class BinaryFieldTests(TestCase):
binary_data = b"\x00\x46\xFE" binary_data = b"\x00\x46\xfe"
def test_set_and_retrieve(self): def test_set_and_retrieve(self):
data_set = ( data_set = (

View File

@ -309,7 +309,7 @@ class ExclusionConstraintTests(PostgreSQLTestCase):
def test_invalid_expressions(self): def test_invalid_expressions(self):
msg = "The expressions must be a list of 2-tuples." msg = "The expressions must be a list of 2-tuples."
for expressions in (["foo"], [("foo")], [("foo_1", "foo_2", "foo_3")]): for expressions in (["foo"], ["foo"], [("foo_1", "foo_2", "foo_3")]):
with self.subTest(expressions), self.assertRaisesMessage(ValueError, msg): with self.subTest(expressions), self.assertRaisesMessage(ValueError, msg):
ExclusionConstraint( ExclusionConstraint(
index_type="GIST", index_type="GIST",

View File

@ -257,7 +257,7 @@ uuid_obj = uuid.uuid4()
test_data = [ test_data = [
# Format: (test helper, PK value, Model Class, data) # Format: (test helper, PK value, Model Class, data)
(data_obj, 1, BinaryData, memoryview(b"\x05\xFD\x00")), (data_obj, 1, BinaryData, memoryview(b"\x05\xfd\x00")),
(data_obj, 5, BooleanData, True), (data_obj, 5, BooleanData, True),
(data_obj, 6, BooleanData, False), (data_obj, 6, BooleanData, False),
(data_obj, 7, BooleanData, None), (data_obj, 7, BooleanData, None),

View File

@ -70,7 +70,7 @@ class XmlSerializerTestCase(SerializersTestBase, TestCase):
msg = "Article.headline (pk:%s) contains unserializable characters" % self.a1.pk msg = "Article.headline (pk:%s) contains unserializable characters" % self.a1.pk
with self.assertRaisesMessage(ValueError, msg): with self.assertRaisesMessage(ValueError, msg):
serializers.serialize(self.serializer_name, [self.a1]) serializers.serialize(self.serializer_name, [self.a1])
self.a1.headline = "HT \u0009, LF \u000A, and CR \u000D are allowed" self.a1.headline = "HT \u0009, LF \u000a, and CR \u000d are allowed"
self.assertIn( self.assertIn(
"HT \t, LF \n, and CR \r are allowed", "HT \t, LF \n, and CR \r are allowed",
serializers.serialize(self.serializer_name, [self.a1]), serializers.serialize(self.serializer_name, [self.a1]),

View File

@ -9,7 +9,7 @@ from django.utils.functional import lazystr
from django.utils.text import format_lazy from django.utils.text import format_lazy
from django.utils.translation import gettext_lazy, override from django.utils.translation import gettext_lazy, override
IS_WIDE_BUILD = len("\U0001F4A9") == 1 IS_WIDE_BUILD = len("\U0001f4a9") == 1
class TestUtilsText(SimpleTestCase): class TestUtilsText(SimpleTestCase):
@ -76,16 +76,16 @@ class TestUtilsText(SimpleTestCase):
# Ensure the final length is calculated correctly when there are # Ensure the final length is calculated correctly when there are
# combining characters with no precomposed form, and that combining # combining characters with no precomposed form, and that combining
# characters are not split up. # characters are not split up.
truncator = text.Truncator("-B\u030AB\u030A----8") truncator = text.Truncator("-B\u030aB\u030a----8")
self.assertEqual("-B\u030A", truncator.chars(3)) self.assertEqual("-B\u030a", truncator.chars(3))
self.assertEqual("-B\u030AB\u030A-…", truncator.chars(5)) self.assertEqual("-B\u030aB\u030a-…", truncator.chars(5))
self.assertEqual("-B\u030AB\u030A----8", truncator.chars(8)) self.assertEqual("-B\u030aB\u030a----8", truncator.chars(8))
# Ensure the length of the end text is correctly calculated when it # Ensure the length of the end text is correctly calculated when it
# contains combining characters with no precomposed form. # contains combining characters with no precomposed form.
truncator = text.Truncator("-----") truncator = text.Truncator("-----")
self.assertEqual("---B\u030A", truncator.chars(4, "B\u030A")) self.assertEqual("---B\u030a", truncator.chars(4, "B\u030a"))
self.assertEqual("-----", truncator.chars(5, "B\u030A")) self.assertEqual("-----", truncator.chars(5, "B\u030a"))
# Make a best effort to shorten to the desired length, but requesting # Make a best effort to shorten to the desired length, but requesting
# a length shorter than the ellipsis shouldn't break # a length shorter than the ellipsis shouldn't break