remove a bunch of unnescesarry iterkeys() calls

This commit is contained in:
Alex Gaynor 2012-08-08 07:33:15 -07:00
parent 576ec12f8e
commit 4c97101b1f
25 changed files with 42 additions and 42 deletions

View File

@ -158,7 +158,7 @@ class UserSettingsHolder(BaseSettings):
return getattr(self.default_settings, name) return getattr(self.default_settings, name)
def __dir__(self): def __dir__(self):
return list(six.iterkeys(self.__dict__)) + dir(self.default_settings) return list(self.__dict__) + dir(self.default_settings)
# For Python < 2.6: # For Python < 2.6:
__members__ = property(lambda self: self.__dir__()) __members__ = property(lambda self: self.__dir__())

View File

@ -425,7 +425,7 @@ class ModelAdmin(BaseModelAdmin):
if self.declared_fieldsets: if self.declared_fieldsets:
return self.declared_fieldsets return self.declared_fieldsets
form = self.get_form(request, obj) form = self.get_form(request, obj)
fields = list(six.iterkeys(form.base_fields)) + list(self.get_readonly_fields(request, obj)) fields = list(form.base_fields) + list(self.get_readonly_fields(request, obj))
return [(None, {'fields': fields})] return [(None, {'fields': fields})]
def get_form(self, request, obj=None, **kwargs): def get_form(self, request, obj=None, **kwargs):
@ -1415,7 +1415,7 @@ class InlineModelAdmin(BaseModelAdmin):
if self.declared_fieldsets: if self.declared_fieldsets:
return self.declared_fieldsets return self.declared_fieldsets
form = self.get_formset(request, obj).form form = self.get_formset(request, obj).form
fields = list(six.iterkeys(form.base_fields)) + list(self.get_readonly_fields(request, obj)) fields = list(form.base_fields) + list(self.get_readonly_fields(request, obj))
return [(None, {'fields': fields})] return [(None, {'fields': fields})]
def queryset(self, request): def queryset(self, request):

View File

@ -126,7 +126,7 @@ def result_headers(cl):
if i in ordering_field_columns: if i in ordering_field_columns:
sorted = True sorted = True
order_type = ordering_field_columns.get(i).lower() order_type = ordering_field_columns.get(i).lower()
sort_priority = list(six.iterkeys(ordering_field_columns)).index(i) + 1 sort_priority = list(ordering_field_columns).index(i) + 1
th_classes.append('sorted %sending' % order_type) th_classes.append('sorted %sending' % order_type)
new_order_type = {'asc': 'desc', 'desc': 'asc'}[order_type] new_order_type = {'asc': 'desc', 'desc': 'asc'}[order_type]

View File

@ -129,7 +129,7 @@ class UserAdmin(admin.ModelAdmin):
else: else:
form = self.change_password_form(user) form = self.change_password_form(user)
fieldsets = [(None, {'fields': list(six.iterkeys(form.base_fields))})] fieldsets = [(None, {'fields': list(form.base_fields)})]
adminForm = admin.helpers.AdminForm(form, fieldsets, {}) adminForm = admin.helpers.AdminForm(form, fieldsets, {})
context = { context = {

View File

@ -204,7 +204,7 @@ class PasswordChangeFormTest(TestCase):
def test_field_order(self): def test_field_order(self):
# Regression test - check the order of fields: # Regression test - check the order of fields:
user = User.objects.get(username='testclient') user = User.objects.get(username='testclient')
self.assertEqual(list(six.iterkeys(PasswordChangeForm(user, {}).fields)), self.assertEqual(list(PasswordChangeForm(user, {}).fields),
['old_password', 'new_password1', 'new_password2']) ['old_password', 'new_password1', 'new_password2'])

View File

@ -44,7 +44,7 @@ class StepsHelper(object):
@property @property
def all(self): def all(self):
"Returns the names of all steps/forms." "Returns the names of all steps/forms."
return list(six.iterkeys(self._wizard.get_form_list())) return list(self._wizard.get_form_list())
@property @property
def count(self): def count(self):

View File

@ -32,7 +32,7 @@ class MySQLOperations(DatabaseOperations, BaseSpatialOperations):
'within' : 'MBRWithin', 'within' : 'MBRWithin',
} }
gis_terms = dict([(term, None) for term in list(six.iterkeys(geometry_functions)) + ['isnull']]) gis_terms = dict([(term, None) for term in list(geometry_functions) + ['isnull']])
def geo_db_type(self, f): def geo_db_type(self, f):
return f.geom_type return f.geom_type

View File

@ -128,7 +128,7 @@ class OracleOperations(DatabaseOperations, BaseSpatialOperations):
geometry_functions.update(distance_functions) geometry_functions.update(distance_functions)
gis_terms = ['isnull'] gis_terms = ['isnull']
gis_terms += list(six.iterkeys(geometry_functions)) gis_terms += list(geometry_functions)
gis_terms = dict([(term, None) for term in gis_terms]) gis_terms = dict([(term, None) for term in gis_terms])
truncate_params = {'relate' : None} truncate_params = {'relate' : None}

View File

@ -217,8 +217,8 @@ class PostGISOperations(DatabaseOperations, BaseSpatialOperations):
# Creating a dictionary lookup of all GIS terms for PostGIS. # Creating a dictionary lookup of all GIS terms for PostGIS.
gis_terms = ['isnull'] gis_terms = ['isnull']
gis_terms += list(six.iterkeys(self.geometry_operators)) gis_terms += list(self.geometry_operators)
gis_terms += list(six.iterkeys(self.geometry_functions)) gis_terms += list(self.geometry_functions)
self.gis_terms = dict([(term, None) for term in gis_terms]) self.gis_terms = dict([(term, None) for term in gis_terms])
self.area = prefix + 'Area' self.area = prefix + 'Area'

View File

@ -131,7 +131,7 @@ class SpatiaLiteOperations(DatabaseOperations, BaseSpatialOperations):
# Creating the GIS terms dictionary. # Creating the GIS terms dictionary.
gis_terms = ['isnull'] gis_terms = ['isnull']
gis_terms += list(six.iterkeys(self.geometry_functions)) gis_terms += list(self.geometry_functions)
self.gis_terms = dict([(term, None) for term in gis_terms]) self.gis_terms = dict([(term, None) for term in gis_terms])
if version >= (2, 4, 0): if version >= (2, 4, 0):

View File

@ -26,7 +26,7 @@ class GeoQuerySet(QuerySet):
flat = kwargs.pop('flat', False) flat = kwargs.pop('flat', False)
if kwargs: if kwargs:
raise TypeError('Unexpected keyword arguments to values_list: %s' raise TypeError('Unexpected keyword arguments to values_list: %s'
% (list(six.iterkeys(kwargs)),)) % (list(kwargs),))
if flat and len(fields) > 1: if flat and len(fields) > 1:
raise TypeError("'flat' is not valid when values_list is called with more than one field.") raise TypeError("'flat' is not valid when values_list is called with more than one field.")
return self._clone(klass=GeoValuesListQuerySet, setup=True, flat=flat, return self._clone(klass=GeoValuesListQuerySet, setup=True, flat=flat,

View File

@ -171,7 +171,7 @@ class GeoSQLCompiler(compiler.SQLCompiler):
objects. objects.
""" """
values = [] values = []
aliases = list(six.iterkeys(self.query.extra_select)) aliases = list(self.query.extra_select)
# Have to set a starting row number offset that is used for # Have to set a starting row number offset that is used for
# determining the correct starting row index -- needed for # determining the correct starting row index -- needed for

View File

@ -295,7 +295,7 @@ class ManagementUtility(object):
except IndexError: except IndexError:
curr = '' curr = ''
subcommands = list(six.iterkeys(get_commands())) + ['help'] subcommands = list(get_commands()) + ['help']
options = [('--help', None)] options = [('--help', None)]
# subcommand # subcommand

View File

@ -76,7 +76,7 @@ def get_serializer(format):
def get_serializer_formats(): def get_serializer_formats():
if not _serializers: if not _serializers:
_load_serializers() _load_serializers()
return list(six.iterkeys(_serializers)) return list(_serializers)
def get_public_serializer_formats(): def get_public_serializer_formats():
if not _serializers: if not _serializers:

View File

@ -138,7 +138,7 @@ def ip_address_validators(protocol, unpack_ipv4):
return ip_address_validator_map[protocol.lower()] return ip_address_validator_map[protocol.lower()]
except KeyError: except KeyError:
raise ValueError("The protocol '%s' is unknown. Supported: %s" raise ValueError("The protocol '%s' is unknown. Supported: %s"
% (protocol, list(six.iterkeys(ip_address_validator_map)))) % (protocol, list(ip_address_validator_map)))
comma_separated_int_list_re = re.compile('^[\d,]+$') comma_separated_int_list_re = re.compile('^[\d,]+$')
validate_comma_separated_integer_list = RegexValidator(comma_separated_int_list_re, _('Enter only digits separated by commas.'), 'invalid') validate_comma_separated_integer_list = RegexValidator(comma_separated_int_list_re, _('Enter only digits separated by commas.'), 'invalid')

View File

@ -388,14 +388,14 @@ class Model(six.with_metaclass(ModelBase, object)):
setattr(self, field.attname, val) setattr(self, field.attname, val)
if kwargs: if kwargs:
for prop in list(six.iterkeys(kwargs)): for prop in list(kwargs):
try: try:
if isinstance(getattr(self.__class__, prop), property): if isinstance(getattr(self.__class__, prop), property):
setattr(self, prop, kwargs.pop(prop)) setattr(self, prop, kwargs.pop(prop))
except AttributeError: except AttributeError:
pass pass
if kwargs: if kwargs:
raise TypeError("'%s' is an invalid keyword argument for this function" % list(six.iterkeys(kwargs))[0]) raise TypeError("'%s' is an invalid keyword argument for this function" % list(kwargs)[0])
super(Model, self).__init__() super(Model, self).__init__()
signals.post_init.send(sender=self.__class__, instance=self) signals.post_init.send(sender=self.__class__, instance=self)

View File

@ -207,7 +207,7 @@ class Collector(object):
def sort(self): def sort(self):
sorted_models = [] sorted_models = []
concrete_models = set() concrete_models = set()
models = list(six.iterkeys(self.data)) models = list(self.data)
while len(sorted_models) < len(models): while len(sorted_models) < len(models):
found = False found = False
for model in models: for model in models:

View File

@ -489,7 +489,7 @@ class Field(object):
# Many of the subclass-specific formfield arguments (min_value, # Many of the subclass-specific formfield arguments (min_value,
# max_value) don't apply for choice fields, so be sure to only pass # max_value) don't apply for choice fields, so be sure to only pass
# the values that TypedChoiceField will understand. # the values that TypedChoiceField will understand.
for k in list(six.iterkeys(kwargs)): for k in list(kwargs):
if k not in ('coerce', 'empty_value', 'choices', 'required', if k not in ('coerce', 'empty_value', 'choices', 'required',
'widget', 'label', 'initial', 'help_text', 'widget', 'label', 'initial', 'help_text',
'error_messages', 'show_hidden_initial'): 'error_messages', 'show_hidden_initial'):

View File

@ -241,7 +241,7 @@ class SingleRelatedObjectDescriptor(object):
rel_obj_attr = attrgetter(self.related.field.attname) rel_obj_attr = attrgetter(self.related.field.attname)
instance_attr = lambda obj: obj._get_pk_val() instance_attr = lambda obj: obj._get_pk_val()
instances_dict = dict((instance_attr(inst), inst) for inst in instances) instances_dict = dict((instance_attr(inst), inst) for inst in instances)
params = {'%s__pk__in' % self.related.field.name: list(six.iterkeys(instances_dict))} params = {'%s__pk__in' % self.related.field.name: list(instances_dict)}
qs = self.get_query_set(instance=instances[0]).filter(**params) qs = self.get_query_set(instance=instances[0]).filter(**params)
# Since we're going to assign directly in the cache, # Since we're going to assign directly in the cache,
# we must manage the reverse relation cache manually. # we must manage the reverse relation cache manually.
@ -335,9 +335,9 @@ class ReverseSingleRelatedObjectDescriptor(object):
instance_attr = attrgetter(self.field.attname) instance_attr = attrgetter(self.field.attname)
instances_dict = dict((instance_attr(inst), inst) for inst in instances) instances_dict = dict((instance_attr(inst), inst) for inst in instances)
if other_field.rel: if other_field.rel:
params = {'%s__pk__in' % self.field.rel.field_name: list(six.iterkeys(instances_dict))} params = {'%s__pk__in' % self.field.rel.field_name: list(instances_dict)}
else: else:
params = {'%s__in' % self.field.rel.field_name: list(six.iterkeys(instances_dict))} params = {'%s__in' % self.field.rel.field_name: list(instances_dict)}
qs = self.get_query_set(instance=instances[0]).filter(**params) qs = self.get_query_set(instance=instances[0]).filter(**params)
# Since we're going to assign directly in the cache, # Since we're going to assign directly in the cache,
# we must manage the reverse relation cache manually. # we must manage the reverse relation cache manually.
@ -488,7 +488,7 @@ class ForeignRelatedObjectsDescriptor(object):
instance_attr = attrgetter(attname) instance_attr = attrgetter(attname)
instances_dict = dict((instance_attr(inst), inst) for inst in instances) instances_dict = dict((instance_attr(inst), inst) for inst in instances)
db = self._db or router.db_for_read(self.model, instance=instances[0]) db = self._db or router.db_for_read(self.model, instance=instances[0])
query = {'%s__%s__in' % (rel_field.name, attname): list(six.iterkeys(instances_dict))} query = {'%s__%s__in' % (rel_field.name, attname): list(instances_dict)}
qs = super(RelatedManager, self).get_query_set().using(db).filter(**query) qs = super(RelatedManager, self).get_query_set().using(db).filter(**query)
# Since we just bypassed this class' get_query_set(), we must manage # Since we just bypassed this class' get_query_set(), we must manage
# the reverse relation manually. # the reverse relation manually.

View File

@ -258,7 +258,7 @@ class Options(object):
self._m2m_cache self._m2m_cache
except AttributeError: except AttributeError:
self._fill_m2m_cache() self._fill_m2m_cache()
return list(six.iterkeys(self._m2m_cache)) return list(self._m2m_cache)
many_to_many = property(_many_to_many) many_to_many = property(_many_to_many)
def get_m2m_with_model(self): def get_m2m_with_model(self):
@ -416,7 +416,7 @@ class Options(object):
cache = self._fill_related_many_to_many_cache() cache = self._fill_related_many_to_many_cache()
if local_only: if local_only:
return [k for k, v in cache.items() if not v] return [k for k, v in cache.items() if not v]
return list(six.iterkeys(cache)) return list(cache)
def get_all_related_m2m_objects_with_model(self): def get_all_related_m2m_objects_with_model(self):
""" """

View File

@ -246,8 +246,8 @@ class QuerySet(object):
requested = None requested = None
max_depth = self.query.max_depth max_depth = self.query.max_depth
extra_select = list(six.iterkeys(self.query.extra_select)) extra_select = list(self.query.extra_select)
aggregate_select = list(six.iterkeys(self.query.aggregate_select)) aggregate_select = list(self.query.aggregate_select)
only_load = self.query.get_loaded_field_names() only_load = self.query.get_loaded_field_names()
if not fill_cache: if not fill_cache:
@ -594,7 +594,7 @@ class QuerySet(object):
flat = kwargs.pop('flat', False) flat = kwargs.pop('flat', False)
if kwargs: if kwargs:
raise TypeError('Unexpected keyword arguments to values_list: %s' raise TypeError('Unexpected keyword arguments to values_list: %s'
% (list(six.iterkeys(kwargs)),)) % (list(kwargs),))
if flat and len(fields) > 1: if flat and len(fields) > 1:
raise TypeError("'flat' is not valid when values_list is called with more than one field.") raise TypeError("'flat' is not valid when values_list is called with more than one field.")
return self._clone(klass=ValuesListQuerySet, setup=True, flat=flat, return self._clone(klass=ValuesListQuerySet, setup=True, flat=flat,
@ -694,7 +694,7 @@ class QuerySet(object):
depth = kwargs.pop('depth', 0) depth = kwargs.pop('depth', 0)
if kwargs: if kwargs:
raise TypeError('Unexpected keyword arguments to select_related: %s' raise TypeError('Unexpected keyword arguments to select_related: %s'
% (list(six.iterkeys(kwargs)),)) % (list(kwargs),))
obj = self._clone() obj = self._clone()
if fields: if fields:
if depth: if depth:
@ -752,7 +752,7 @@ class QuerySet(object):
obj = self._clone() obj = self._clone()
obj._setup_aggregate_query(list(six.iterkeys(kwargs))) obj._setup_aggregate_query(list(kwargs))
# Add the aggregates to the query # Add the aggregates to the query
for (alias, aggregate_expr) in kwargs.items(): for (alias, aggregate_expr) in kwargs.items():
@ -967,9 +967,9 @@ class ValuesQuerySet(QuerySet):
def iterator(self): def iterator(self):
# Purge any extra columns that haven't been explicitly asked for # Purge any extra columns that haven't been explicitly asked for
extra_names = list(six.iterkeys(self.query.extra_select)) extra_names = list(self.query.extra_select)
field_names = self.field_names field_names = self.field_names
aggregate_names = list(six.iterkeys(self.query.aggregate_select)) aggregate_names = list(self.query.aggregate_select)
names = extra_names + field_names + aggregate_names names = extra_names + field_names + aggregate_names
@ -1098,9 +1098,9 @@ class ValuesListQuerySet(ValuesQuerySet):
# When extra(select=...) or an annotation is involved, the extra # When extra(select=...) or an annotation is involved, the extra
# cols are always at the start of the row, and we need to reorder # cols are always at the start of the row, and we need to reorder
# the fields to match the order in self._fields. # the fields to match the order in self._fields.
extra_names = list(six.iterkeys(self.query.extra_select)) extra_names = list(self.query.extra_select)
field_names = self.field_names field_names = self.field_names
aggregate_names = list(six.iterkeys(self.query.aggregate_select)) aggregate_names = list(self.query.aggregate_select)
names = extra_names + field_names + aggregate_names names = extra_names + field_names + aggregate_names

View File

@ -1303,7 +1303,7 @@ class Query(object):
field, model, direct, m2m = opts.get_field_by_name(f.name) field, model, direct, m2m = opts.get_field_by_name(f.name)
break break
else: else:
names = opts.get_all_field_names() + list(six.iterkeys(self.aggregate_select)) names = opts.get_all_field_names() + list(self.aggregate_select)
raise FieldError("Cannot resolve keyword %r into field. " raise FieldError("Cannot resolve keyword %r into field. "
"Choices are: %s" % (name, ", ".join(names))) "Choices are: %s" % (name, ", ".join(names)))
@ -1661,8 +1661,8 @@ class Query(object):
# from the model on which the lookup failed. # from the model on which the lookup failed.
raise raise
else: else:
names = sorted(opts.get_all_field_names() + list(six.iterkeys(self.extra)) names = sorted(opts.get_all_field_names() + list(self.extra)
+ list(six.iterkeys(self.aggregate_select))) + list(self.aggregate_select))
raise FieldError("Cannot resolve keyword %r into field. " raise FieldError("Cannot resolve keyword %r into field. "
"Choices are: %s" % (name, ", ".join(names))) "Choices are: %s" % (name, ", ".join(names)))
self.remove_inherited_models() self.remove_inherited_models()

View File

@ -1189,7 +1189,7 @@ def templatetag(parser, token):
if tag not in TemplateTagNode.mapping: if tag not in TemplateTagNode.mapping:
raise TemplateSyntaxError("Invalid templatetag argument: '%s'." raise TemplateSyntaxError("Invalid templatetag argument: '%s'."
" Must be one of: %s" % " Must be one of: %s" %
(tag, list(six.iterkeys(TemplateTagNode.mapping)))) (tag, list(TemplateTagNode.mapping)))
return TemplateTagNode(tag) return TemplateTagNode(tag)
@register.tag @register.tag

View File

@ -129,7 +129,7 @@ class SortedDict(dict):
data = list(data) data = list(data)
super(SortedDict, self).__init__(data) super(SortedDict, self).__init__(data)
if isinstance(data, dict): if isinstance(data, dict):
self.keyOrder = list(six.iterkeys(data)) self.keyOrder = list(data)
else: else:
self.keyOrder = [] self.keyOrder = []
seen = set() seen = set()

View File

@ -363,7 +363,7 @@ class DictConfigurator(BaseConfigurator):
#which were in the previous configuration but #which were in the previous configuration but
#which are not in the new configuration. #which are not in the new configuration.
root = logging.root root = logging.root
existing = list(six.iterkeys(root.manager.loggerDict)) existing = list(root.manager.loggerDict)
#The list needs to be sorted so that we can #The list needs to be sorted so that we can
#avoid disabling child loggers of explicitly #avoid disabling child loggers of explicitly
#named loggers. With a sorted list it is easier #named loggers. With a sorted list it is easier