Avoided creating temporary lists for obtaining the first item.

This commit is contained in:
Sergey Fedoseev 2017-07-31 20:02:23 +05:00 committed by Tim Graham
parent 0f905e4b44
commit aadd3aeb2b
8 changed files with 17 additions and 19 deletions

View File

@ -156,9 +156,9 @@ class MigrationLoader:
if key[0] in self.migrated_apps: if key[0] in self.migrated_apps:
try: try:
if key[1] == "__first__": if key[1] == "__first__":
return list(self.graph.root_nodes(key[0]))[0] return self.graph.root_nodes(key[0])[0]
else: # "__latest__" else: # "__latest__"
return list(self.graph.leaf_nodes(key[0]))[0] return self.graph.leaf_nodes(key[0])[0]
except IndexError: except IndexError:
if self.ignore_no_migrations: if self.ignore_no_migrations:
return None return None

View File

@ -48,7 +48,7 @@ class MigrationQuestioner:
elif hasattr(migrations_module, "__path__"): elif hasattr(migrations_module, "__path__"):
if len(migrations_module.__path__) > 1: if len(migrations_module.__path__) > 1:
return False return False
filenames = os.listdir(list(migrations_module.__path__)[0]) filenames = os.listdir(migrations_module.__path__[0])
return not any(x.endswith(".py") for x in filenames if x != "__init__.py") return not any(x.endswith(".py") for x in filenames if x != "__init__.py")
def ask_not_null_addition(self, field_name, model_name): def ask_not_null_addition(self, field_name, model_name):

View File

@ -481,8 +481,8 @@ class Model(metaclass=ModelBase):
del kwargs[prop] del kwargs[prop]
except (AttributeError, FieldDoesNotExist): except (AttributeError, FieldDoesNotExist):
pass pass
if kwargs: for kwarg in kwargs:
raise TypeError("'%s' is an invalid keyword argument for this function" % list(kwargs)[0]) raise TypeError("'%s' is an invalid keyword argument for this function" % kwarg)
super().__init__() super().__init__()
post_init.send(sender=cls, instance=self) post_init.send(sender=cls, instance=self)

View File

@ -275,7 +275,8 @@ class QuerySet:
qs = self._clone() qs = self._clone()
qs.query.set_limits(k, k + 1) qs.query.set_limits(k, k + 1)
return list(qs)[0] qs._fetch_all()
return qs._result_cache[0]
def __and__(self, other): def __and__(self, other):
self._merge_sanity_check(other) self._merge_sanity_check(other)
@ -548,17 +549,13 @@ class QuerySet:
def first(self): def first(self):
"""Return the first object of a query or None if no match is found.""" """Return the first object of a query or None if no match is found."""
objects = list((self if self.ordered else self.order_by('pk'))[:1]) for obj in (self if self.ordered else self.order_by('pk'))[:1]:
if objects: return obj
return objects[0]
return None
def last(self): def last(self):
"""Return the last object of a query or None if no match is found.""" """Return the last object of a query or None if no match is found."""
objects = list((self.reverse() if self.ordered else self.order_by('-pk'))[:1]) for obj in (self.reverse() if self.ordered else self.order_by('-pk'))[:1]:
if objects: return obj
return objects[0]
return None
def in_bulk(self, id_list=None, *, field_name='pk'): def in_bulk(self, id_list=None, *, field_name='pk'):
""" """

View File

@ -217,7 +217,8 @@ class Query:
@cached_property @cached_property
def base_table(self): def base_table(self):
return list(self.alias_map)[0] if self.alias_map else None for alias in self.alias_map:
return alias
def __str__(self): def __str__(self):
""" """

View File

@ -95,7 +95,7 @@ class ErrorList(UserList, list):
def get_json_data(self, escape_html=False): def get_json_data(self, escape_html=False):
errors = [] errors = []
for error in self.as_data(): for error in self.as_data():
message = list(error)[0] message = next(iter(error))
errors.append({ errors.append({
'message': escape(message) if escape_html else message, 'message': escape(message) if escape_html else message,
'code': error.code or '', 'code': error.code or '',
@ -133,7 +133,7 @@ class ErrorList(UserList, list):
def __getitem__(self, i): def __getitem__(self, i):
error = self.data[i] error = self.data[i]
if isinstance(error, ValidationError): if isinstance(error, ValidationError):
return list(error)[0] return next(iter(error))
return error return error
def __reduce_ex__(self, *args, **kwargs): def __reduce_ex__(self, *args, **kwargs):

View File

@ -500,7 +500,7 @@ def do_block_translate(parser, token):
options[option] = value options[option] = value
if 'count' in options: if 'count' in options:
countervar, counter = list(options['count'].items())[0] countervar, counter = next(iter(options['count'].items()))
else: else:
countervar, counter = None, None countervar, counter = None, None
if 'context' in options: if 'context' in options:

View File

@ -155,7 +155,7 @@ class TestFirstLast(TestCase):
# We know that we've broken the __iter__ method, so the queryset # We know that we've broken the __iter__ method, so the queryset
# should always raise an exception. # should always raise an exception.
with self.assertRaises(IndexError): with self.assertRaises(IndexError):
IndexErrorArticle.objects.all()[0] IndexErrorArticle.objects.all()[:10:2]
with self.assertRaises(IndexError): with self.assertRaises(IndexError):
IndexErrorArticle.objects.all().first() IndexErrorArticle.objects.all().first()
with self.assertRaises(IndexError): with self.assertRaises(IndexError):