1
0
mirror of https://github.com/django/django.git synced 2024-12-22 17:16:24 +00:00

Used more augmented assignment statements.

Identified using the following command:

$ git grep -I '\(\<[_a-zA-Z0-9]\+\>\) *= *\1 *[-+/*^%&|<>@]'
This commit is contained in:
Nick Pope 2022-01-28 20:15:53 +00:00 committed by Mariusz Felisiak
parent a320aab512
commit d3cb91db87
28 changed files with 47 additions and 50 deletions

View File

@ -95,7 +95,7 @@ class AdminForm:
def media(self): def media(self):
media = self.form.media media = self.form.media
for fs in self: for fs in self:
media = media + fs.media media += fs.media
return media return media
@ -456,7 +456,7 @@ class InlineAdminFormSet:
def media(self): def media(self):
media = self.opts.media + self.formset.media media = self.opts.media + self.formset.media
for fs in self: for fs in self:
media = media + fs.media media += fs.media
return media return media

View File

@ -1840,7 +1840,7 @@ class ModelAdmin(BaseModelAdmin):
request, formsets, inline_instances, obj request, formsets, inline_instances, obj
) )
for inline_formset in inline_formsets: for inline_formset in inline_formsets:
media = media + inline_formset.media media += inline_formset.media
if add: if add:
title = _("Add %s") title = _("Add %s")

View File

@ -119,11 +119,11 @@ function findPosY(obj) {
let result = '', i = 0; let result = '', i = 0;
while (i < format.length) { while (i < format.length) {
if (format.charAt(i) === '%') { if (format.charAt(i) === '%') {
result = result + fields[format.charAt(i + 1)]; result += fields[format.charAt(i + 1)];
++i; ++i;
} }
else { else {
result = result + format.charAt(i); result += format.charAt(i);
} }
++i; ++i;
} }

View File

@ -32,7 +32,7 @@ def update_proxy_model_permissions(apps, schema_editor, reverse=False):
] ]
permissions_query = Q(codename__in=proxy_default_permissions_codenames) permissions_query = Q(codename__in=proxy_default_permissions_codenames)
for codename, name in opts.permissions: for codename, name in opts.permissions:
permissions_query = permissions_query | Q(codename=codename, name=name) permissions_query |= Q(codename=codename, name=name)
content_type_manager = ContentType.objects.db_manager(alias) content_type_manager = ContentType.objects.db_manager(alias)
concrete_content_type = content_type_manager.get_for_model( concrete_content_type = content_type_manager.get_for_model(
Model, for_concrete_model=True Model, for_concrete_model=True

View File

@ -997,7 +997,7 @@ class BaseDatabaseSchemaEditor:
if not four_way_default_alteration: if not four_way_default_alteration:
# If we don't have to do a 4-way default alteration we can # If we don't have to do a 4-way default alteration we can
# directly run a (NOT) NULL alteration # directly run a (NOT) NULL alteration
actions = actions + null_actions actions += null_actions
# Combine actions together if we can (e.g. postgres) # Combine actions together if we can (e.g. postgres)
if self.connection.features.supports_combined_alters and actions: if self.connection.features.supports_combined_alters and actions:
sql, params = tuple(zip(*actions)) sql, params = tuple(zip(*actions))

View File

@ -528,7 +528,7 @@ class FormatStylePlaceholderCursor:
elif hasattr(params, "keys"): elif hasattr(params, "keys"):
# Handle params as dict # Handle params as dict
args = {k: ":%s" % k for k in params} args = {k: ":%s" % k for k in params}
query = query % args query %= args
elif unify_by_values and params: elif unify_by_values and params:
# Handle params as a dict with unified query parameters by their # Handle params as a dict with unified query parameters by their
# values. It can be used only in single query execute() because # values. It can be used only in single query execute() because
@ -542,11 +542,11 @@ class FormatStylePlaceholderCursor:
} }
args = [params_dict[param] for param in params] args = [params_dict[param] for param in params]
params = {value: key for key, value in params_dict.items()} params = {value: key for key, value in params_dict.items()}
query = query % tuple(args) query %= tuple(args)
else: else:
# Handle params as sequence # Handle params as sequence
args = [(":arg%d" % i) for i in range(len(params))] args = [(":arg%d" % i) for i in range(len(params))]
query = query % tuple(args) query %= tuple(args)
return query, self._format_params(params) return query, self._format_params(params)
def execute(self, query, params=None): def execute(self, query, params=None):

View File

@ -166,7 +166,7 @@ class DatabaseIntrospection(BaseDatabaseIntrospection):
for desc in cursor.description: for desc in cursor.description:
name = desc[0] name = desc[0]
internal_size, default, collation, is_autofield, is_json = field_map[name] internal_size, default, collation, is_autofield, is_json = field_map[name]
name = name % {} # cx_Oracle, for some reason, doubles percent signs. name %= {} # cx_Oracle, for some reason, doubles percent signs.
description.append( description.append(
FieldInfo( FieldInfo(
self.identifier_converter(name), self.identifier_converter(name),

View File

@ -134,7 +134,7 @@ def _sqlite_date_trunc(lookup_type, dt, tzname, conn_tzname):
elif lookup_type == "month": elif lookup_type == "month":
return f"{dt.year:04d}-{dt.month:02d}-01" return f"{dt.year:04d}-{dt.month:02d}-01"
elif lookup_type == "week": elif lookup_type == "week":
dt = dt - timedelta(days=dt.weekday()) dt -= timedelta(days=dt.weekday())
return f"{dt.year:04d}-{dt.month:02d}-{dt.day:02d}" return f"{dt.year:04d}-{dt.month:02d}-{dt.day:02d}"
elif lookup_type == "day": elif lookup_type == "day":
return f"{dt.year:04d}-{dt.month:02d}-{dt.day:02d}" return f"{dt.year:04d}-{dt.month:02d}-{dt.day:02d}"
@ -205,7 +205,7 @@ def _sqlite_datetime_trunc(lookup_type, dt, tzname, conn_tzname):
elif lookup_type == "month": elif lookup_type == "month":
return f"{dt.year:04d}-{dt.month:02d}-01 00:00:00" return f"{dt.year:04d}-{dt.month:02d}-01 00:00:00"
elif lookup_type == "week": elif lookup_type == "week":
dt = dt - timedelta(days=dt.weekday()) dt -= timedelta(days=dt.weekday())
return f"{dt.year:04d}-{dt.month:02d}-{dt.day:02d} 00:00:00" return f"{dt.year:04d}-{dt.month:02d}-{dt.day:02d} 00:00:00"
elif lookup_type == "day": elif lookup_type == "day":
return f"{dt.year:04d}-{dt.month:02d}-{dt.day:02d} 00:00:00" return f"{dt.year:04d}-{dt.month:02d}-{dt.day:02d} 00:00:00"

View File

@ -292,7 +292,7 @@ class JSONExact(lookups.Exact):
rhs_params = ["null"] rhs_params = ["null"]
if connection.vendor == "mysql": if connection.vendor == "mysql":
func = ["JSON_EXTRACT(%s, '$')"] * len(rhs_params) func = ["JSON_EXTRACT(%s, '$')"] * len(rhs_params)
rhs = rhs % tuple(func) rhs %= tuple(func)
return rhs, rhs_params return rhs, rhs_params
@ -455,9 +455,9 @@ class KeyTransformIn(lookups.In):
value = json.loads(param) value = json.loads(param)
sql = "%s(JSON_OBJECT('value' VALUE %%s FORMAT JSON), '$.value')" sql = "%s(JSON_OBJECT('value' VALUE %%s FORMAT JSON), '$.value')"
if isinstance(value, (list, dict)): if isinstance(value, (list, dict)):
sql = sql % "JSON_QUERY" sql %= "JSON_QUERY"
else: else:
sql = sql % "JSON_VALUE" sql %= "JSON_VALUE"
elif connection.vendor == "mysql" or ( elif connection.vendor == "mysql" or (
connection.vendor == "sqlite" connection.vendor == "sqlite"
and params[0] not in connection.ops.jsonfield_datatype_values and params[0] not in connection.ops.jsonfield_datatype_values
@ -482,7 +482,7 @@ class KeyTransformExact(JSONExact):
func.append(sql % "JSON_QUERY") func.append(sql % "JSON_QUERY")
else: else:
func.append(sql % "JSON_VALUE") func.append(sql % "JSON_VALUE")
rhs = rhs % tuple(func) rhs %= tuple(func)
elif connection.vendor == "sqlite": elif connection.vendor == "sqlite":
func = [] func = []
for value in rhs_params: for value in rhs_params:
@ -490,7 +490,7 @@ class KeyTransformExact(JSONExact):
func.append("%s") func.append("%s")
else: else:
func.append("JSON_EXTRACT(%s, '$')") func.append("JSON_EXTRACT(%s, '$')")
rhs = rhs % tuple(func) rhs %= tuple(func)
return rhs, rhs_params return rhs, rhs_params
def as_oracle(self, compiler, connection): def as_oracle(self, compiler, connection):

View File

@ -355,7 +355,7 @@ class RelatedField(FieldCacheMixin, Field):
else: else:
related_name = self.opts.default_related_name related_name = self.opts.default_related_name
if related_name: if related_name:
related_name = related_name % { related_name %= {
"class": cls.__name__.lower(), "class": cls.__name__.lower(),
"model_name": cls._meta.model_name.lower(), "model_name": cls._meta.model_name.lower(),
"app_label": cls._meta.app_label.lower(), "app_label": cls._meta.app_label.lower(),

View File

@ -2046,7 +2046,7 @@ class SQLAggregateCompiler(SQLCompiler):
elide_empty=self.elide_empty, elide_empty=self.elide_empty,
).as_sql(with_col_aliases=True) ).as_sql(with_col_aliases=True)
sql = "SELECT %s FROM (%s) subquery" % (sql, inner_query_sql) sql = "SELECT %s FROM (%s) subquery" % (sql, inner_query_sql)
params = params + inner_query_params params += inner_query_params
return sql, params return sql, params

View File

@ -1531,7 +1531,7 @@ class Query(BaseExpression):
): ):
"""Add a Q-object to the current filter.""" """Add a Q-object to the current filter."""
connector = q_object.connector connector = q_object.connector
current_negated = current_negated ^ q_object.negated current_negated ^= q_object.negated
branch_negated = branch_negated or q_object.negated branch_negated = branch_negated or q_object.negated
target_clause = WhereNode(connector=connector, negated=q_object.negated) target_clause = WhereNode(connector=connector, negated=q_object.negated)
joinpromoter = JoinPromoter( joinpromoter = JoinPromoter(

View File

@ -492,7 +492,7 @@ class BaseForm(RenderableFormMixin):
"""Return all media required to render the widgets on this form.""" """Return all media required to render the widgets on this form."""
media = Media() media = Media()
for field in self.fields.values(): for field in self.fields.values():
media = media + field.widget.media media += field.widget.media
return media return media
def is_multipart(self): def is_multipart(self):

View File

@ -316,7 +316,7 @@ class ModelFormMetaclass(DeclarativeFieldsMetaclass):
missing_fields = none_model_fields.difference(new_class.declared_fields) missing_fields = none_model_fields.difference(new_class.declared_fields)
if missing_fields: if missing_fields:
message = "Unknown field(s) (%s) specified for %s" message = "Unknown field(s) (%s) specified for %s"
message = message % (", ".join(missing_fields), opts.model.__name__) message %= (", ".join(missing_fields), opts.model.__name__)
raise FieldError(message) raise FieldError(message)
# Override default model fields with any custom declared ones # Override default model fields with any custom declared ones
# (plus, include all the other declared fields). # (plus, include all the other declared fields).

View File

@ -207,7 +207,7 @@ def media_property(cls):
else: else:
m = Media() m = Media()
for medium in extend: for medium in extend:
m = m + base[medium] m += base[medium]
return m + Media(definition) return m + Media(definition)
return Media(definition) return Media(definition)
return base return base
@ -945,7 +945,7 @@ class MultiWidget(Widget):
""" """
media = Media() media = Media()
for w in self.widgets: for w in self.widgets:
media = media + w.media media += w.media
return media return media
media = property(_get_media) media = property(_get_media)

View File

@ -241,7 +241,7 @@ class HttpResponseBase:
# Add one second so the date matches exactly (a fraction of # Add one second so the date matches exactly (a fraction of
# time gets lost between converting to a timedelta and # time gets lost between converting to a timedelta and
# then the date string). # then the date string).
delta = delta + datetime.timedelta(seconds=1) delta += datetime.timedelta(seconds=1)
# Just set max_age - the max_age logic will set expires. # Just set max_age - the max_age logic will set expires.
expires = None expires = None
if max_age is not None: if max_age is not None:

View File

@ -38,9 +38,9 @@ class SecurityMiddleware(MiddlewareMixin):
): ):
sts_header = "max-age=%s" % self.sts_seconds sts_header = "max-age=%s" % self.sts_seconds
if self.sts_include_subdomains: if self.sts_include_subdomains:
sts_header = sts_header + "; includeSubDomains" sts_header += "; includeSubDomains"
if self.sts_preload: if self.sts_preload:
sts_header = sts_header + "; preload" sts_header += "; preload"
response.headers["Strict-Transport-Security"] = sts_header response.headers["Strict-Transport-Security"] = sts_header
if self.content_type_nosniff: if self.content_type_nosniff:

View File

@ -187,7 +187,7 @@ class BlockTranslateNode(Node):
data = {v: render_value(v) for v in vars} data = {v: render_value(v) for v in vars}
context.pop() context.pop()
try: try:
result = result % data result %= data
except (KeyError, ValueError): except (KeyError, ValueError):
if nested: if nested:
# Either string is malformed, or it's a bug # Either string is malformed, or it's a bug

View File

@ -593,7 +593,7 @@ class modify_settings(override_settings):
if isinstance(items, str): if isinstance(items, str):
items = [items] items = [items]
if action == "append": if action == "append":
value = value + [item for item in items if item not in value] value += [item for item in items if item not in value]
elif action == "prepend": elif action == "prepend":
value = [item for item in items if item not in value] + value value = [item for item in items if item not in value] + value
elif action == "remove": elif action == "remove":

View File

@ -70,7 +70,7 @@ def reverse(viewname, urlconf=None, args=None, kwargs=None, current_app=None):
try: try:
extra, resolver = resolver.namespace_dict[ns] extra, resolver = resolver.namespace_dict[ns]
resolved_path.append(ns) resolved_path.append(ns)
ns_pattern = ns_pattern + extra ns_pattern += extra
ns_converters.update(resolver.pattern.converters) ns_converters.update(resolver.pattern.converters)
except KeyError as key: except KeyError as key:
if resolved_path: if resolved_path:

View File

@ -95,10 +95,10 @@ def strftime(dt, fmt):
# 6 years to get into the 28-year repeat cycle # 6 years to get into the 28-year repeat cycle
delta = 2000 - year delta = 2000 - year
off = 6 * (delta // 100 + delta // 400) off = 6 * (delta // 100 + delta // 400)
year = year + off year += off
# Move to around the year 2000 # Move to around the year 2000
year = year + ((2000 - year) // 28) * 28 year += ((2000 - year) // 28) * 28
timetuple = dt.timetuple() timetuple = dt.timetuple()
s1 = time.strftime(fmt, (year,) + timetuple[1:]) s1 = time.strftime(fmt, (year,) + timetuple[1:])
sites1 = _findall(s1, str(year)) sites1 = _findall(s1, str(year))

View File

@ -7,10 +7,10 @@ def _get_duration_components(duration):
microseconds = duration.microseconds microseconds = duration.microseconds
minutes = seconds // 60 minutes = seconds // 60
seconds = seconds % 60 seconds %= 60
hours = minutes // 60 hours = minutes // 60
minutes = minutes % 60 minutes %= 60
return days, hours, minutes, seconds, microseconds return days, hours, minutes, seconds, microseconds

View File

@ -81,7 +81,7 @@ def format(
else: else:
int_part, dec_part = str_number, "" int_part, dec_part = str_number, ""
if decimal_pos is not None: if decimal_pos is not None:
dec_part = dec_part + ("0" * (decimal_pos - len(dec_part))) dec_part += "0" * (decimal_pos - len(dec_part))
dec_part = dec_part and decimal_sep + dec_part dec_part = dec_part and decimal_sep + dec_part
# grouping # grouping
if use_grouping: if use_grouping:

View File

@ -334,7 +334,7 @@ def _is_pytz_zone(tz):
_PYTZ_BASE_CLASSES = (pytz.tzinfo.BaseTzInfo, pytz._FixedOffset) _PYTZ_BASE_CLASSES = (pytz.tzinfo.BaseTzInfo, pytz._FixedOffset)
# In releases prior to 2018.4, pytz.UTC was not a subclass of BaseTzInfo # In releases prior to 2018.4, pytz.UTC was not a subclass of BaseTzInfo
if not isinstance(pytz.UTC, pytz._FixedOffset): if not isinstance(pytz.UTC, pytz._FixedOffset):
_PYTZ_BASE_CLASSES = _PYTZ_BASE_CLASSES + (type(pytz.UTC),) _PYTZ_BASE_CLASSES += (type(pytz.UTC),)
return isinstance(tz, _PYTZ_BASE_CLASSES) return isinstance(tz, _PYTZ_BASE_CLASSES)

View File

@ -149,7 +149,7 @@ def lazy_number(func, resultclass, number=None, **kwargs):
number_value = rhs number_value = rhs
translated = self._translate(number_value) translated = self._translate(number_value)
try: try:
translated = translated % rhs translated %= rhs
except TypeError: except TypeError:
# String doesn't contain a placeholder for the number. # String doesn't contain a placeholder for the number.
pass pass

View File

@ -1908,11 +1908,9 @@ class SeleniumTests(AdminSeleniumTestCase):
"border-top-%s", "border-top-%s",
] ]
for prop in border_properties: for prop in border_properties:
prop = prop % "width" self.assertEqual(element.value_of_css_property(prop % "width"), width)
self.assertEqual(element.value_of_css_property(prop), width)
for prop in border_properties: for prop in border_properties:
prop = prop % "style" self.assertEqual(element.value_of_css_property(prop % "style"), style)
self.assertEqual(element.value_of_css_property(prop), style)
# Convert hex color to rgb. # Convert hex color to rgb.
self.assertRegex(color, "#[0-9a-f]{6}") self.assertRegex(color, "#[0-9a-f]{6}")
r, g, b = int(color[1:3], 16), int(color[3:5], 16), int(color[5:], 16) r, g, b = int(color[1:3], 16), int(color[3:5], 16), int(color[5:], 16)
@ -1923,8 +1921,7 @@ class SeleniumTests(AdminSeleniumTestCase):
"rgba(%d, %d, %d, 1)" % (r, g, b), "rgba(%d, %d, %d, 1)" % (r, g, b),
] ]
for prop in border_properties: for prop in border_properties:
prop = prop % "color" self.assertIn(element.value_of_css_property(prop % "color"), colors)
self.assertIn(element.value_of_css_property(prop), colors)
def test_inline_formset_error_input_border(self): def test_inline_formset_error_input_border(self):
from selenium.webdriver.common.by import By from selenium.webdriver.common.by import By

View File

@ -643,7 +643,7 @@ class FormsMediaTestCase(SimpleTestCase):
self.assertEqual( self.assertEqual(
merged._css, {"screen": ["c.css", "a.css"], "all": ["d.css", "e.css"]} merged._css, {"screen": ["c.css", "a.css"], "all": ["d.css", "e.css"]}
) )
merged = merged + widget3 merged += widget3
# widget3 contains an explicit ordering of c.css and a.css. # widget3 contains an explicit ordering of c.css and a.css.
self.assertEqual( self.assertEqual(
merged._css, merged._css,

View File

@ -390,7 +390,7 @@ class LoaderTests(TestCase):
loader.build_graph() loader.build_graph()
plan = set(loader.graph.forwards_plan(("app1", "4_auto"))) plan = set(loader.graph.forwards_plan(("app1", "4_auto")))
plan = plan - loader.applied_migrations.keys() plan -= loader.applied_migrations.keys()
expected_plan = { expected_plan = {
("app2", "1_squashed_2"), ("app2", "1_squashed_2"),
("app1", "3_auto"), ("app1", "3_auto"),
@ -529,7 +529,7 @@ class LoaderTests(TestCase):
# Load with nothing applied: both migrations squashed. # Load with nothing applied: both migrations squashed.
loader.build_graph() loader.build_graph()
plan = set(loader.graph.forwards_plan(("app1", "4_auto"))) plan = set(loader.graph.forwards_plan(("app1", "4_auto")))
plan = plan - loader.applied_migrations.keys() plan -= loader.applied_migrations.keys()
expected_plan = { expected_plan = {
("app1", "1_auto"), ("app1", "1_auto"),
("app2", "1_squashed_2"), ("app2", "1_squashed_2"),
@ -548,7 +548,7 @@ class LoaderTests(TestCase):
loader.replace_migrations = False loader.replace_migrations = False
loader.build_graph() loader.build_graph()
plan = set(loader.graph.forwards_plan(("app1", "3_auto"))) plan = set(loader.graph.forwards_plan(("app1", "3_auto")))
plan = plan - loader.applied_migrations.keys() plan -= loader.applied_migrations.keys()
expected_plan = { expected_plan = {
("app1", "1_auto"), ("app1", "1_auto"),
("app2", "1_auto"), ("app2", "1_auto"),
@ -564,7 +564,7 @@ class LoaderTests(TestCase):
self.record_applied(recorder, "app1", "2_auto") self.record_applied(recorder, "app1", "2_auto")
loader.build_graph() loader.build_graph()
plan = set(loader.graph.forwards_plan(("app1", "4_auto"))) plan = set(loader.graph.forwards_plan(("app1", "4_auto")))
plan = plan - loader.applied_migrations.keys() plan -= loader.applied_migrations.keys()
expected_plan = { expected_plan = {
("app2", "1_squashed_2"), ("app2", "1_squashed_2"),
("app1", "3_auto"), ("app1", "3_auto"),
@ -576,7 +576,7 @@ class LoaderTests(TestCase):
self.record_applied(recorder, "app2", "1_auto") self.record_applied(recorder, "app2", "1_auto")
loader.build_graph() loader.build_graph()
plan = set(loader.graph.forwards_plan(("app1", "4_auto"))) plan = set(loader.graph.forwards_plan(("app1", "4_auto")))
plan = plan - loader.applied_migrations.keys() plan -= loader.applied_migrations.keys()
expected_plan = { expected_plan = {
("app2", "2_auto"), ("app2", "2_auto"),
("app1", "3_auto"), ("app1", "3_auto"),