diff options
| author | Sergey Fedoseev <fedoseev.sergey@gmail.com> | 2018-09-28 18:57:12 +0500 |
|---|---|---|
| committer | Tim Graham <timograham@gmail.com> | 2018-09-28 09:57:12 -0400 |
| commit | 8ef8bc0f64c463684268a7c55f3d3da4de066c0d (patch) | |
| tree | 9c3ab782c6382bdbc91363d0dd5513df83381903 /django | |
| parent | 4fc8fb7ddaad495d45d53df58b2d13115857b3c7 (diff) | |
Refs #28909 -- Simplifed code using unpacking generalizations.
Diffstat (limited to 'django')
24 files changed, 56 insertions, 68 deletions
diff --git a/django/apps/registry.py b/django/apps/registry.py index d7ac81af82..464d69a89d 100644 --- a/django/apps/registry.py +++ b/django/apps/registry.py @@ -389,7 +389,7 @@ class Apps: # to lazy_model_operation() along with the remaining model args and # repeat until all models are loaded and all arguments are applied. else: - next_model, more_models = model_keys[0], model_keys[1:] + next_model, *more_models = model_keys # This will be executed after the class corresponding to next_model # has been imported and registered. The `func` attribute provides diff --git a/django/conf/__init__.py b/django/conf/__init__.py index 05c603786e..062975b1c6 100644 --- a/django/conf/__init__.py +++ b/django/conf/__init__.py @@ -182,7 +182,7 @@ class UserSettingsHolder: def __dir__(self): return sorted( - s for s in list(self.__dict__) + dir(self.default_settings) + s for s in [*self.__dict__, *dir(self.default_settings)] if s not in self._deleted ) diff --git a/django/contrib/admin/options.py b/django/contrib/admin/options.py index fb2fcdd9d6..43a90b302c 100644 --- a/django/contrib/admin/options.py +++ b/django/contrib/admin/options.py @@ -256,7 +256,7 @@ class BaseModelAdmin(metaclass=forms.MediaDefiningClass): kwargs['widget'] = AutocompleteSelectMultiple(db_field.remote_field, self.admin_site, using=db) elif db_field.name in self.raw_id_fields: kwargs['widget'] = widgets.ManyToManyRawIdWidget(db_field.remote_field, self.admin_site, using=db) - elif db_field.name in list(self.filter_vertical) + list(self.filter_horizontal): + elif db_field.name in [*self.filter_vertical, *self.filter_horizontal]: kwargs['widget'] = widgets.FilteredSelectMultiple( db_field.verbose_name, db_field.name in self.filter_vertical @@ -318,7 +318,7 @@ class BaseModelAdmin(metaclass=forms.MediaDefiningClass): return self.fields # _get_form_for_get_fields() is implemented in subclasses. form = self._get_form_for_get_fields(request, obj) - return list(form.base_fields) + list(self.get_readonly_fields(request, obj)) + return [*form.base_fields, *self.get_readonly_fields(request, obj)] def get_fieldsets(self, request, obj=None): """ @@ -724,7 +724,7 @@ class ModelAdmin(BaseModelAdmin): list_display_links = self.get_list_display_links(request, list_display) # Add the action checkboxes if any actions are available. if self.get_actions(request): - list_display = ['action_checkbox'] + list(list_display) + list_display = ['action_checkbox', *list_display] sortable_by = self.get_sortable_by(request) ChangeList = self.get_changelist(request) return ChangeList( diff --git a/django/contrib/admindocs/views.py b/django/contrib/admindocs/views.py index 4a70801774..0474c38fd4 100644 --- a/django/contrib/admindocs/views.py +++ b/django/contrib/admindocs/views.py @@ -278,7 +278,7 @@ class ModelDetailView(BaseAdminDocsView): # join it with '='. Use repr() so that strings will be # correctly displayed. print_arguments = ', '.join([ - '='.join(list(arg_el[:1]) + [repr(el) for el in arg_el[1:]]) + '='.join([arg_el[0], *map(repr, arg_el[1:])]) for arg_el in arguments ]) methods.append({ diff --git a/django/contrib/auth/management/__init__.py b/django/contrib/auth/management/__init__.py index 7c9618c63b..14c25a7399 100644 --- a/django/contrib/auth/management/__init__.py +++ b/django/contrib/auth/management/__init__.py @@ -15,9 +15,7 @@ def _get_all_permissions(opts): """ Return (codename, name) for all permissions in the given opts. """ - builtin = _get_builtin_permissions(opts) - custom = list(opts.permissions) - return builtin + custom + return [*_get_builtin_permissions(opts), *opts.permissions] def _get_builtin_permissions(opts): diff --git a/django/contrib/gis/geos/mutable_list.py b/django/contrib/gis/geos/mutable_list.py index 3e67906623..b04a2128af 100644 --- a/django/contrib/gis/geos/mutable_list.py +++ b/django/contrib/gis/geos/mutable_list.py @@ -109,11 +109,11 @@ class ListMixin: # ### Special methods for arithmetic operations ### def __add__(self, other): 'add another list-like object' - return self.__class__(list(self) + list(other)) + return self.__class__([*self, *other]) def __radd__(self, other): 'add to another list-like object' - return other.__class__(list(other) + list(self)) + return other.__class__([*other, *self]) def __iadd__(self, other): 'add another list-like object to self' diff --git a/django/contrib/gis/geos/polygon.py b/django/contrib/gis/geos/polygon.py index 9ed3b946bb..d857bf00f3 100644 --- a/django/contrib/gis/geos/polygon.py +++ b/django/contrib/gis/geos/polygon.py @@ -31,8 +31,7 @@ class Polygon(GEOSGeometry): return # Getting the ext_ring and init_holes parameters from the argument list - ext_ring = args[0] - init_holes = args[1:] + ext_ring, *init_holes = args n_holes = len(init_holes) # If initialized as Polygon(shell, (LinearRing, LinearRing)) [for backward-compatibility] @@ -44,7 +43,7 @@ class Polygon(GEOSGeometry): init_holes = init_holes[0] n_holes = len(init_holes) - polygon = self._create_polygon(n_holes + 1, (ext_ring,) + init_holes) + polygon = self._create_polygon(n_holes + 1, [ext_ring, *init_holes]) super().__init__(polygon, **kwargs) def __iter__(self): diff --git a/django/contrib/gis/serializers/geojson.py b/django/contrib/gis/serializers/geojson.py index 4a62ea4251..3cd015479c 100644 --- a/django/contrib/gis/serializers/geojson.py +++ b/django/contrib/gis/serializers/geojson.py @@ -13,7 +13,7 @@ class Serializer(JSONSerializer): self.srid = self.json_kwargs.pop('srid', 4326) if (self.selected_fields is not None and self.geometry_field is not None and self.geometry_field not in self.selected_fields): - self.selected_fields = list(self.selected_fields) + [self.geometry_field] + self.selected_fields = [*self.selected_fields, self.geometry_field] def start_serialization(self): self._init_options() diff --git a/django/contrib/postgres/fields/array.py b/django/contrib/postgres/fields/array.py index a6079466af..b87575235e 100644 --- a/django/contrib/postgres/fields/array.py +++ b/django/contrib/postgres/fields/array.py @@ -28,8 +28,7 @@ class ArrayField(CheckFieldDefaultMixin, Field): self.base_field = base_field self.size = size if self.size: - self.default_validators = self.default_validators[:] - self.default_validators.append(ArrayMaxLengthValidator(self.size)) + self.default_validators = [*self.default_validators, ArrayMaxLengthValidator(self.size)] # For performance, only add a from_db_value() method if the base field # implements it. if hasattr(self.base_field, 'from_db_value'): diff --git a/django/core/handlers/wsgi.py b/django/core/handlers/wsgi.py index 0b6be82607..47b008a004 100644 --- a/django/core/handlers/wsgi.py +++ b/django/core/handlers/wsgi.py @@ -143,9 +143,10 @@ class WSGIHandler(base.BaseHandler): response._handler_class = self.__class__ status = '%d %s' % (response.status_code, response.reason_phrase) - response_headers = list(response.items()) - for c in response.cookies.values(): - response_headers.append(('Set-Cookie', c.output(header=''))) + response_headers = [ + *response.items(), + *(('Set-Cookie', c.output(header='')) for c in response.cookies.values()), + ] start_response(status, response_headers) if getattr(response, 'file_to_stream', None) is not None and environ.get('wsgi.file_wrapper'): response = environ['wsgi.file_wrapper'](response.file_to_stream) diff --git a/django/core/management/__init__.py b/django/core/management/__init__.py index b4c28b3e62..e0c924bdac 100644 --- a/django/core/management/__init__.py +++ b/django/core/management/__init__.py @@ -257,7 +257,7 @@ class ManagementUtility: except IndexError: curr = '' - subcommands = list(get_commands()) + ['help'] + subcommands = [*get_commands(), 'help'] options = [('--help', False)] # subcommand diff --git a/django/db/migrations/operations/models.py b/django/db/migrations/operations/models.py index 7ca54e7f75..9b13bb9a3c 100644 --- a/django/db/migrations/operations/models.py +++ b/django/db/migrations/operations/models.py @@ -735,9 +735,7 @@ class AddIndex(IndexOperation): def state_forwards(self, app_label, state): model_state = state.models[app_label, self.model_name_lower] - indexes = list(model_state.options[self.option_name]) - indexes.append(self.index.clone()) - model_state.options[self.option_name] = indexes + model_state.options[self.option_name] = [*model_state.options[self.option_name], self.index.clone()] state.reload_model(app_label, self.model_name_lower, delay=True) def database_forwards(self, app_label, schema_editor, from_state, to_state): @@ -820,9 +818,7 @@ class AddConstraint(IndexOperation): def state_forwards(self, app_label, state): model_state = state.models[app_label, self.model_name_lower] - constraints = list(model_state.options[self.option_name]) - constraints.append(self.constraint) - model_state.options[self.option_name] = constraints + model_state.options[self.option_name] = [*model_state.options[self.option_name], self.constraint] def database_forwards(self, app_label, schema_editor, from_state, to_state): model = to_state.apps.get_model(app_label, self.model_name) diff --git a/django/db/migrations/state.py b/django/db/migrations/state.py index ea2db0e5af..b2671d0819 100644 --- a/django/db/migrations/state.py +++ b/django/db/migrations/state.py @@ -261,14 +261,14 @@ class StateApps(Apps): self.real_models.append(ModelState.from_model(model, exclude_rels=True)) # Populate the app registry with a stub for each application. app_labels = {model_state.app_label for model_state in models.values()} - app_configs = [AppConfigStub(label) for label in sorted(real_apps + list(app_labels))] + app_configs = [AppConfigStub(label) for label in sorted([*real_apps, *app_labels])] super().__init__(app_configs) # The lock gets in the way of copying as implemented in clone(), which # is called whenever Django duplicates a StateApps before updating it. self._lock = None - self.render_multiple(list(models.values()) + self.real_models) + self.render_multiple([*models.values(), *self.real_models]) # There shouldn't be any operations pending at this point. from django.core.checks.model_checks import _check_lazy_references diff --git a/django/db/models/expressions.py b/django/db/models/expressions.py index 9a9c036f86..2532431821 100644 --- a/django/db/models/expressions.py +++ b/django/db/models/expressions.py @@ -947,8 +947,7 @@ class Case(Expression): return self.cases + [self.default] def set_source_expressions(self, exprs): - self.cases = exprs[:-1] - self.default = exprs[-1] + *self.cases, self.default = exprs def resolve_expression(self, query=None, allow_joins=True, reuse=None, summarize=False, for_save=False): c = self.copy() diff --git a/django/db/models/query.py b/django/db/models/query.py index db1dc998fa..d0bec5a35f 100644 --- a/django/db/models/query.py +++ b/django/db/models/query.py @@ -96,13 +96,12 @@ class ValuesIterable(BaseIterable): query = queryset.query compiler = query.get_compiler(queryset.db) - field_names = list(query.values_select) - extra_names = list(query.extra_select) - annotation_names = list(query.annotation_select) - # extra(select=...) cols are always at the start of the row. - names = extra_names + field_names + annotation_names - + names = [ + *query.extra_select, + *query.values_select, + *query.annotation_select, + ] indexes = range(len(names)) for row in compiler.results_iter(chunked_fetch=self.chunked_fetch, chunk_size=self.chunk_size): yield {names[i]: row[i] for i in indexes} @@ -120,14 +119,13 @@ class ValuesListIterable(BaseIterable): compiler = query.get_compiler(queryset.db) if queryset._fields: - field_names = list(query.values_select) - extra_names = list(query.extra_select) - annotation_names = list(query.annotation_select) - # extra(select=...) cols are always at the start of the row. - names = extra_names + field_names + annotation_names - - fields = list(queryset._fields) + [f for f in annotation_names if f not in queryset._fields] + names = [ + *query.extra_select, + *query.values_select, + *query.annotation_select, + ] + fields = [*queryset._fields, *(f for f in query.annotation_select if f not in queryset._fields)] if fields != names: # Reorder according to fields. index_map = {name: idx for idx, name in enumerate(names)} @@ -352,7 +350,7 @@ class QuerySet: """ if self.query.distinct_fields: raise NotImplementedError("aggregate() + distinct(fields) not implemented.") - self._validate_values_are_expressions(args + tuple(kwargs.values()), method_name='aggregate') + self._validate_values_are_expressions((*args, *kwargs.values()), method_name='aggregate') for arg in args: # The default_alias property raises TypeError if default_alias # can't be set automatically or AttributeError if it isn't an diff --git a/django/db/models/query_utils.py b/django/db/models/query_utils.py index 8c41116d69..ce311639da 100644 --- a/django/db/models/query_utils.py +++ b/django/db/models/query_utils.py @@ -58,7 +58,7 @@ class Q(tree.Node): def __init__(self, *args, **kwargs): connector = kwargs.pop('_connector', None) negated = kwargs.pop('_negated', False) - super().__init__(children=list(args) + sorted(kwargs.items()), connector=connector, negated=negated) + super().__init__(children=[*args, *sorted(kwargs.items())], connector=connector, negated=negated) def _combine(self, other, conn): if not isinstance(other, Q): diff --git a/django/db/models/sql/query.py b/django/db/models/sql/query.py index 81f6f196d3..beb57f8ecd 100644 --- a/django/db/models/sql/query.py +++ b/django/db/models/sql/query.py @@ -1096,12 +1096,11 @@ class Query: and get_transform(). """ # __exact is the default lookup if one isn't given. - lookups = lookups or ['exact'] - for name in lookups[:-1]: + *transforms, lookup_name = lookups or ['exact'] + for name in transforms: lhs = self.try_transform(lhs, name) # First try get_lookup() so that the lookup takes precedence if the lhs # supports both transform and lookup for the name. - lookup_name = lookups[-1] lookup_class = lhs.get_lookup(lookup_name) if not lookup_class: if lhs.field.is_relation: @@ -1406,11 +1405,11 @@ class Query: # one step. pos -= 1 if pos == -1 or fail_on_missing: - field_names = list(get_field_names_from_opts(opts)) - available = sorted( - field_names + list(self.annotation_select) + - list(self._filtered_relations) - ) + available = sorted([ + *get_field_names_from_opts(opts), + *self.annotation_select, + *self._filtered_relations, + ]) raise FieldError("Cannot resolve keyword '%s' into field. " "Choices are: %s" % (name, ", ".join(available))) break @@ -1776,10 +1775,10 @@ class Query: # from the model on which the lookup failed. raise else: - names = sorted( - list(get_field_names_from_opts(opts)) + list(self.extra) + - list(self.annotation_select) + list(self._filtered_relations) - ) + names = sorted([ + *get_field_names_from_opts(opts), *self.extra, + *self.annotation_select, *self._filtered_relations + ]) raise FieldError("Cannot resolve keyword %r into field. " "Choices are: %s" % (name, ", ".join(names))) diff --git a/django/template/engine.py b/django/template/engine.py index 381d656bbb..dfaa67ba12 100644 --- a/django/template/engine.py +++ b/django/template/engine.py @@ -107,8 +107,7 @@ class Engine: def find_template_loader(self, loader): if isinstance(loader, (tuple, list)): - args = list(loader[1:]) - loader = loader[0] + loader, *args = loader else: args = [] diff --git a/django/test/html.py b/django/test/html.py index c01f73c1fb..3b55b52861 100644 --- a/django/test/html.py +++ b/django/test/html.py @@ -72,7 +72,7 @@ class Element: return self.children == element.children def __hash__(self): - return hash((self.name,) + tuple(a for a in self.attributes)) + return hash((self.name, *(a for a in self.attributes))) def _count(self, element, count=True): if not isinstance(element, str): diff --git a/django/test/testcases.py b/django/test/testcases.py index 7aec0b406b..f327e53561 100644 --- a/django/test/testcases.py +++ b/django/test/testcases.py @@ -614,8 +614,7 @@ class SimpleTestCase(unittest.TestCase): def _assertFooMessage(self, func, cm_attr, expected_exception, expected_message, *args, **kwargs): callable_obj = None if args: - callable_obj = args[0] - args = args[1:] + callable_obj, *args = args cm = self._assert_raises_or_warns_cm(func, cm_attr, expected_exception, expected_message) # Assertion used in context manager fashion. if callable_obj is None: diff --git a/django/test/utils.py b/django/test/utils.py index e9852436aa..618fde8f36 100644 --- a/django/test/utils.py +++ b/django/test/utils.py @@ -120,7 +120,7 @@ def setup_test_environment(debug=None): saved_data.allowed_hosts = settings.ALLOWED_HOSTS # Add the default host of the test client. - settings.ALLOWED_HOSTS = list(settings.ALLOWED_HOSTS) + ['testserver'] + settings.ALLOWED_HOSTS = [*settings.ALLOWED_HOSTS, 'testserver'] saved_data.debug = settings.DEBUG settings.DEBUG = debug diff --git a/django/utils/html.py b/django/utils/html.py index b230c5faec..e68e25443f 100644 --- a/django/utils/html.py +++ b/django/utils/html.py @@ -133,8 +133,9 @@ def format_html_join(sep, format_string, args_generator): for u in users)) """ return mark_safe(conditional_escape(sep).join( - format_html(format_string, *tuple(args)) - for args in args_generator)) + format_html(format_string, *args) + for args in args_generator + )) @keep_lazy_text diff --git a/django/utils/translation/trans_real.py b/django/utils/translation/trans_real.py index 266843aa1d..c06ca34153 100644 --- a/django/utils/translation/trans_real.py +++ b/django/utils/translation/trans_real.py @@ -360,7 +360,7 @@ def all_locale_paths(): locale_path = os.path.join(app_config.path, 'locale') if os.path.exists(locale_path): app_paths.append(locale_path) - return [globalpath] + list(settings.LOCALE_PATHS) + app_paths + return [globalpath, *settings.LOCALE_PATHS, *app_paths] @functools.lru_cache(maxsize=1000) diff --git a/django/utils/tree.py b/django/utils/tree.py index 421ad5cd3c..cb45c7ee29 100644 --- a/django/utils/tree.py +++ b/django/utils/tree.py @@ -71,7 +71,7 @@ class Node: ) def __hash__(self): - return hash((self.__class__, self.connector, self.negated) + tuple([ + return hash((self.__class__, self.connector, self.negated, *[ tuple(child) if isinstance(child, list) else child for child in self.children ])) |
