1
0
mirror of https://github.com/django/django.git synced 2024-12-23 01:25:58 +00:00

Avoided creation of temporary sets.

This commit is contained in:
Sergey Fedoseev 2017-07-29 19:16:43 +05:00 committed by Tim Graham
parent b306c0c1a3
commit 38988f289f
11 changed files with 20 additions and 21 deletions

View File

@ -268,7 +268,7 @@ class ChangeList:
# ordering fields so we can guarantee a deterministic order across all # ordering fields so we can guarantee a deterministic order across all
# database backends. # database backends.
pk_name = self.lookup_opts.pk.name pk_name = self.lookup_opts.pk.name
if not (set(ordering) & {'pk', '-pk', pk_name, '-' + pk_name}): if {'pk', '-pk', pk_name, '-' + pk_name}.isdisjoint(ordering):
# The two sets do not intersect, meaning the pk isn't present. So # The two sets do not intersect, meaning the pk isn't present. So
# we add it. # we add it.
ordering.append('-pk') ordering.append('-pk')

View File

@ -52,7 +52,7 @@ class SessionStore(SessionBase):
# Make sure we're not vulnerable to directory traversal. Session keys # Make sure we're not vulnerable to directory traversal. Session keys
# should always be md5s, so they should never contain directory # should always be md5s, so they should never contain directory
# components. # components.
if not set(session_key).issubset(set(VALID_KEY_CHARS)): if not set(session_key).issubset(VALID_KEY_CHARS):
raise InvalidSessionKey( raise InvalidSessionKey(
"Invalid characters in session key") "Invalid characters in session key")

View File

@ -67,7 +67,7 @@ class CheckRegistry:
if tags is not None: if tags is not None:
checks = [check for check in checks checks = [check for check in checks
if hasattr(check, 'tags') and set(check.tags) & set(tags)] if hasattr(check, 'tags') and not set(check.tags).isdisjoint(tags)]
else: else:
# By default, 'database'-tagged checks are not run as they do more # By default, 'database'-tagged checks are not run as they do more
# than mere static code analysis. # than mere static code analysis.

View File

@ -122,7 +122,7 @@ def call_command(command_name, *args, **options):
# Raise an error if any unknown options were passed. # Raise an error if any unknown options were passed.
stealth_options = set(command.base_stealth_options + command.stealth_options) stealth_options = set(command.base_stealth_options + command.stealth_options)
dest_parameters = {action.dest for action in parser._actions} dest_parameters = {action.dest for action in parser._actions}
valid_options = dest_parameters | stealth_options | set(opt_mapping) valid_options = (dest_parameters | stealth_options).union(opt_mapping)
unknown_options = set(options) - valid_options unknown_options = set(options) - valid_options
if unknown_options: if unknown_options:
raise TypeError( raise TypeError(

View File

@ -85,7 +85,7 @@ class Command(BaseCommand):
# Account for excluded locales # Account for excluded locales
locales = locale or all_locales locales = locale or all_locales
locales = set(locales) - set(exclude) locales = set(locales).difference(exclude)
for basedir in basedirs: for basedir in basedirs:
if locales: if locales:

View File

@ -371,7 +371,7 @@ class Command(BaseCommand):
locales = all_locales locales = all_locales
else: else:
locales = locale or all_locales locales = locale or all_locales
locales = set(locales) - set(exclude) locales = set(locales).difference(exclude)
if locales: if locales:
check_programs('msguniq', 'msgmerge', 'msgattrib') check_programs('msguniq', 'msgmerge', 'msgattrib')

View File

@ -451,12 +451,12 @@ class MigrationAutodetector:
""" """
self.renamed_models = {} self.renamed_models = {}
self.renamed_models_rel = {} self.renamed_models_rel = {}
added_models = set(self.new_model_keys) - set(self.old_model_keys) added_models = set(self.new_model_keys).difference(self.old_model_keys)
for app_label, model_name in sorted(added_models): for app_label, model_name in sorted(added_models):
model_state = self.to_state.models[app_label, model_name] model_state = self.to_state.models[app_label, model_name]
model_fields_def = self.only_relation_agnostic_fields(model_state.fields) model_fields_def = self.only_relation_agnostic_fields(model_state.fields)
removed_models = set(self.old_model_keys) - set(self.new_model_keys) removed_models = set(self.old_model_keys).difference(self.new_model_keys)
for rem_app_label, rem_model_name in removed_models: for rem_app_label, rem_model_name in removed_models:
if rem_app_label == app_label: if rem_app_label == app_label:
rem_model_state = self.from_state.models[rem_app_label, rem_model_name] rem_model_state = self.from_state.models[rem_app_label, rem_model_name]
@ -642,7 +642,7 @@ class MigrationAutodetector:
models it's safe to skip all the pointless field stuff and just chuck models it's safe to skip all the pointless field stuff and just chuck
out an operation. out an operation.
""" """
added = set(self.new_proxy_keys) - set(self.old_proxy_keys) added = set(self.new_proxy_keys).difference(self.old_proxy_keys)
for app_label, model_name in sorted(added): for app_label, model_name in sorted(added):
model_state = self.to_state.models[app_label, model_name] model_state = self.to_state.models[app_label, model_name]
assert model_state.options.get("proxy") assert model_state.options.get("proxy")
@ -764,7 +764,7 @@ class MigrationAutodetector:
def generate_deleted_proxies(self): def generate_deleted_proxies(self):
"""Make DeleteModel options for proxy models.""" """Make DeleteModel options for proxy models."""
deleted = set(self.old_proxy_keys) - set(self.new_proxy_keys) deleted = set(self.old_proxy_keys).difference(self.new_proxy_keys)
for app_label, model_name in sorted(deleted): for app_label, model_name in sorted(deleted):
model_state = self.from_state.models[app_label, model_name] model_state = self.from_state.models[app_label, model_name]
assert model_state.options.get("proxy") assert model_state.options.get("proxy")

View File

@ -1044,7 +1044,7 @@ def create_forward_many_to_many_manager(superclass, rel, reverse):
source_field_name: self.related_val[0], source_field_name: self.related_val[0],
'%s__in' % target_field_name: new_ids, '%s__in' % target_field_name: new_ids,
})) }))
new_ids = new_ids - set(vals) new_ids.difference_update(vals)
with transaction.atomic(using=db, savepoint=False): with transaction.atomic(using=db, savepoint=False):
if self.reverse or source_field_name == self.source_field_name: if self.reverse or source_field_name == self.source_field_name:

View File

@ -789,7 +789,7 @@ class Query:
relabelling any references to them in select columns and the where relabelling any references to them in select columns and the where
clause. clause.
""" """
assert set(change_map).intersection(set(change_map.values())) == set() assert set(change_map).isdisjoint(change_map.values())
# 1. Update references in "select" (normal columns plus aliases), # 1. Update references in "select" (normal columns plus aliases),
# "group by" and "where". # "group by" and "where".
@ -975,7 +975,7 @@ class Query:
def prepare_lookup_value(self, value, lookups, can_reuse, allow_joins=True): def prepare_lookup_value(self, value, lookups, can_reuse, allow_joins=True):
# Default lookup if none given is exact. # Default lookup if none given is exact.
used_joins = [] used_joins = set()
if len(lookups) == 0: if len(lookups) == 0:
lookups = ['exact'] lookups = ['exact']
# Interpret '__exact=None' as the sql 'is NULL'; otherwise, reject all # Interpret '__exact=None' as the sql 'is NULL'; otherwise, reject all
@ -987,12 +987,11 @@ class Query:
elif hasattr(value, 'resolve_expression'): elif hasattr(value, 'resolve_expression'):
pre_joins = self.alias_refcount.copy() pre_joins = self.alias_refcount.copy()
value = value.resolve_expression(self, reuse=can_reuse, allow_joins=allow_joins) value = value.resolve_expression(self, reuse=can_reuse, allow_joins=allow_joins)
used_joins = [k for k, v in self.alias_refcount.items() if v > pre_joins.get(k, 0)] used_joins = {k for k, v in self.alias_refcount.items() if v > pre_joins.get(k, 0)}
elif isinstance(value, (list, tuple)): elif isinstance(value, (list, tuple)):
# The items of the iterable may be expressions and therefore need # The items of the iterable may be expressions and therefore need
# to be resolved independently. # to be resolved independently.
processed_values = [] processed_values = []
used_joins = set()
for sub_value in value: for sub_value in value:
if hasattr(sub_value, 'resolve_expression'): if hasattr(sub_value, 'resolve_expression'):
pre_joins = self.alias_refcount.copy() pre_joins = self.alias_refcount.copy()
@ -1172,7 +1171,7 @@ class Query:
# Update used_joins before trimming since they are reused to determine # Update used_joins before trimming since they are reused to determine
# which joins could be later promoted to INNER. # which joins could be later promoted to INNER.
used_joins = set(used_joins).union(set(join_list)) used_joins.update(join_list)
targets, alias, join_list = self.trim_joins(sources, join_list, path) targets, alias, join_list = self.trim_joins(sources, join_list, path)
if can_reuse is not None: if can_reuse is not None:
can_reuse.update(join_list) can_reuse.update(join_list)

View File

@ -258,8 +258,8 @@ class ModelFormMetaclass(DeclarativeFieldsMetaclass):
) )
# make sure opts.fields doesn't specify an invalid field # make sure opts.fields doesn't specify an invalid field
none_model_fields = [k for k, v in fields.items() if not v] none_model_fields = {k for k, v in fields.items() if not v}
missing_fields = set(none_model_fields) - set(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), message = message % (', '.join(missing_fields),
@ -682,8 +682,8 @@ class BaseModelFormSet(BaseFormSet):
for form in valid_forms: for form in valid_forms:
exclude = form._get_validation_exclusions() exclude = form._get_validation_exclusions()
unique_checks, date_checks = form.instance._get_unique_checks(exclude=exclude) unique_checks, date_checks = form.instance._get_unique_checks(exclude=exclude)
all_unique_checks = all_unique_checks.union(set(unique_checks)) all_unique_checks.update(unique_checks)
all_date_checks = all_date_checks.union(set(date_checks)) all_date_checks.update(date_checks)
errors = [] errors = []
# Do each of the unique checks (unique and unique_together) # Do each of the unique checks (unique and unique_together)

View File

@ -436,7 +436,7 @@ class RegexURLResolver(LocaleRegexProvider):
continue continue
candidate_subs = dict(zip(params, text_args)) candidate_subs = dict(zip(params, text_args))
else: else:
if set(kwargs) | set(defaults) != set(params) | set(defaults): if set(kwargs).symmetric_difference(params).difference(defaults):
continue continue
matches = True matches = True
for k, v in defaults.items(): for k, v in defaults.items():