[1.7.x] Corrected many style guide violations that the newest version of flake8 catches

Backport of 778ce245dd from master
This commit is contained in:
Alex Gaynor 2014-03-30 12:11:05 -07:00 committed by Tim Graham
parent 0dad0ca55e
commit 50dddbdfc7
37 changed files with 54 additions and 52 deletions

View File

@ -258,7 +258,7 @@ class BaseModelAdmin(six.with_metaclass(RenameBaseModelAdminMethods)):
})
kwargs['empty_label'] = _('None') if db_field.blank else None
if not 'queryset' in kwargs:
if 'queryset' not in kwargs:
queryset = self.get_field_queryset(db, db_field, request)
if queryset is not None:
kwargs['queryset'] = queryset
@ -282,7 +282,7 @@ class BaseModelAdmin(six.with_metaclass(RenameBaseModelAdminMethods)):
elif db_field.name in (list(self.filter_vertical) + list(self.filter_horizontal)):
kwargs['widget'] = widgets.FilteredSelectMultiple(db_field.verbose_name, (db_field.name in self.filter_vertical))
if not 'queryset' in kwargs:
if 'queryset' not in kwargs:
queryset = self.get_field_queryset(db, db_field, request)
if queryset is not None:
kwargs['queryset'] = queryset

View File

@ -138,7 +138,7 @@ class BaseValidator(object):
raise ImproperlyConfigured("'%s.radio_fields['%s']' "
"is neither an instance of ForeignKey nor does "
"have choices set." % (cls.__name__, field))
if not val in (HORIZONTAL, VERTICAL):
if val not in (HORIZONTAL, VERTICAL):
raise ImproperlyConfigured("'%s.radio_fields['%s']' "
"is neither admin.HORIZONTAL nor admin.VERTICAL."
% (cls.__name__, field))

View File

@ -75,7 +75,7 @@ def get_flatpages(parser, token):
syntax_message = ("%(tag_name)s expects a syntax of %(tag_name)s "
"['url_starts_with'] [for user] as context_name" %
dict(tag_name=bits[0]))
# Must have at 3-6 bits in the tag
# Must have at 3-6 bits in the tag
if len(bits) >= 3 and len(bits) <= 6:
# If there's an even number of bits, there's no prefix

View File

@ -481,14 +481,14 @@ class PostGISOperations(DatabaseOperations, BaseSpatialOperations):
geo_col, db_type = lvalue
if lookup_type in self.geometry_operators:
if field.geography and not lookup_type in self.geography_operators:
if field.geography and lookup_type not in self.geography_operators:
raise ValueError('PostGIS geography does not support the '
'"%s" lookup.' % lookup_type)
# Handling a PostGIS operator.
op = self.geometry_operators[lookup_type]
return op.as_sql(geo_col, self.get_geom_placeholder(field, value))
elif lookup_type in self.geometry_functions:
if field.geography and not lookup_type in self.geography_functions:
if field.geography and lookup_type not in self.geography_functions:
raise ValueError('PostGIS geography type does not support the '
'"%s" lookup.' % lookup_type)

View File

@ -29,11 +29,11 @@ def get_srid_info(srid, connection):
# No `spatial_ref_sys` table in spatial backend (e.g., MySQL).
return None, None, None
if not connection.alias in _srid_cache:
if connection.alias not in _srid_cache:
# Initialize SRID dictionary for database if it doesn't exist.
_srid_cache[connection.alias] = {}
if not srid in _srid_cache[connection.alias]:
if srid not in _srid_cache[connection.alias]:
# Use `SpatialRefSys` model to query for spatial reference info.
sr = SpatialRefSys.objects.using(connection.alias).get(srid=srid)
units, units_name = sr.units
@ -225,7 +225,7 @@ class GeometryField(Field):
'srid': self.srid,
}
defaults.update(kwargs)
if (self.dim > 2 and not 'widget' in kwargs and
if (self.dim > 2 and 'widget' not in kwargs and
not getattr(defaults['form_class'].widget, 'supports_3d', False)):
defaults['widget'] = forms.Textarea
return super(GeometryField, self).formfield(**defaults)

View File

@ -467,7 +467,7 @@ class GeoQuerySet(QuerySet):
# If the `geo_field_type` keyword was used, then enforce that
# type limitation.
if not geo_field_type is None and not isinstance(geo_field, geo_field_type):
if geo_field_type is not None and not isinstance(geo_field, geo_field_type):
raise TypeError('"%s" stored procedures may only be called on %ss.' % (func, geo_field_type.__name__))
# Setting the procedure args.
@ -488,7 +488,7 @@ class GeoQuerySet(QuerySet):
# Checking if there are any geo field type limitations on this
# aggregate (e.g. ST_Makeline only operates on PointFields).
if not geo_field_type is None and not isinstance(geo_field, geo_field_type):
if geo_field_type is not None and not isinstance(geo_field, geo_field_type):
raise TypeError('%s aggregate may only be called on %ss.' % (aggregate.name, geo_field_type.__name__))
# Getting the string expression of the field name, as this is the
@ -766,7 +766,7 @@ class GeoQuerySet(QuerySet):
ForeignKey relation to the current model.
"""
opts = self.model._meta
if not geo_field in opts.fields:
if geo_field not in opts.fields:
# Is this operation going to be on a related geographic field?
# If so, it'll have to be added to the select related information
# (e.g., if 'location__point' was given as the field name).
@ -777,7 +777,7 @@ class GeoQuerySet(QuerySet):
if field == geo_field:
return compiler._field_column(geo_field, rel_table)
raise ValueError("%r not in self.query.related_select_cols" % geo_field)
elif not geo_field in opts.local_fields:
elif geo_field not in opts.local_fields:
# This geographic field is inherited from another model, so we have to
# use the db table for the _parent_ model instead.
tmp_fld, parent_model, direct, m2m = opts.get_field_by_name(geo_field.name)

View File

@ -37,7 +37,7 @@ class GeoFeedMixin(object):
"""
# Getting the Geometry object.
geom = item.get('geometry', None)
if not geom is None:
if geom is not None:
if isinstance(geom, (list, tuple)):
# Special case if a tuple/list was passed in. The tuple may be
# a point or a box
@ -58,7 +58,7 @@ class GeoFeedMixin(object):
else:
raise ValueError('Only should be 2 or 4 numeric elements.')
# If a GeoRSS box was given via tuple.
if not box_coords is None:
if box_coords is not None:
if w3c_geo:
raise ValueError('Cannot use simple GeoRSS box in W3C Geo feeds.')
handler.addQuickElement('georss:box', self.georss_coords(box_coords))

View File

@ -205,7 +205,7 @@ class OGRGeometry(GDALBase):
def _set_coord_dim(self, dim):
"Sets the coordinate dimension of this Geometry."
if not dim in (2, 3):
if dim not in (2, 3):
raise ValueError('Geometry dimension must be either 2 or 3')
capi.set_coord_dim(self.ptr, dim)

View File

@ -42,7 +42,7 @@ class OGRGeomType(object):
if num is None:
raise OGRException('Invalid OGR String Type "%s"' % type_input)
elif isinstance(type_input, int):
if not type_input in self._types:
if type_input not in self._types:
raise OGRException('Invalid OGR Integer Type: %d' % type_input)
num = type_input
else:

View File

@ -195,7 +195,7 @@ class Layer(GDALBase):
Returns a list containing the given field name for every Feature
in the Layer.
"""
if not field_name in self.fields:
if field_name not in self.fields:
raise OGRException('invalid field name: %s' % field_name)
return [feat.get(field_name) for feat in self]

View File

@ -36,7 +36,7 @@ else:
if lib_names:
for lib_name in lib_names:
lib_path = find_library(lib_name)
if not lib_path is None:
if lib_path is not None:
break
if lib_path is None:

View File

@ -43,7 +43,7 @@ else:
if lib_names:
for lib_name in lib_names:
lib_path = find_library(lib_name)
if not lib_path is None:
if lib_path is not None:
break
# No GEOS library could be found.

View File

@ -189,7 +189,7 @@ class WKTWriter(IOBase):
@outdim.setter
def outdim(self, new_dim):
if not new_dim in (2, 3):
if new_dim not in (2, 3):
raise ValueError('WKT output dimension must be 2 or 3')
wkt_writer_set_outdim(self.ptr, new_dim)
@ -214,7 +214,7 @@ class WKBWriter(IOBase):
return wkb_writer_get_byteorder(self.ptr)
def _set_byteorder(self, order):
if not order in (0, 1):
if order not in (0, 1):
raise ValueError('Byte order parameter must be 0 (Big Endian) or 1 (Little Endian).')
wkb_writer_set_byteorder(self.ptr, order)
@ -225,7 +225,7 @@ class WKBWriter(IOBase):
return wkb_writer_get_outdim(self.ptr)
def _set_outdim(self, new_dim):
if not new_dim in (2, 3):
if new_dim not in (2, 3):
raise ValueError('WKB output dimension must be 2 or 3')
wkb_writer_set_outdim(self.ptr, new_dim)

View File

@ -503,7 +503,8 @@ class GEOSTest(unittest.TestCase, TestDataMixin):
del poly
# Access to these rings is OK since they are clones.
s1, s2 = str(ring1), str(ring2)
str(ring1)
str(ring2)
def test_coord_seq(self):
"Testing Coordinate Sequence objects."

View File

@ -239,7 +239,7 @@ class LayerMapping(object):
raise TypeError('ForeignKey mapping must be of dictionary type.')
else:
# Is the model field type supported by LayerMapping?
if not model_field.__class__ in self.FIELD_TYPES:
if model_field.__class__ not in self.FIELD_TYPES:
raise LayerMapError('Django field type "%s" has no OGR mapping (yet).' % fld_name)
# Is the OGR field in the Layer?
@ -277,7 +277,7 @@ class LayerMapping(object):
if isinstance(unique, (list, tuple)):
# List of fields to determine uniqueness with
for attr in unique:
if not attr in self.mapping:
if attr not in self.mapping:
raise ValueError
elif isinstance(unique, six.string_types):
# Only a single field passed in.

View File

@ -312,5 +312,5 @@ class Command(NoArgsCommand):
self.log("Copying '%s'" % source_path, level=1)
with source_storage.open(path) as source_file:
self.storage.save(prefixed_path, source_file)
if not prefixed_path in self.copied_files:
if prefixed_path not in self.copied_files:
self.copied_files.append(prefixed_path)

View File

@ -118,7 +118,7 @@ class Command(NoArgsCommand):
field_type = 'NullBooleanField('
else:
extra_params['blank'] = True
if not field_type in ('TextField(', 'CharField('):
if field_type not in ('TextField(', 'CharField('):
extra_params['null'] = True
field_desc = '%s = %s%s' % (

View File

@ -165,7 +165,7 @@ class Signer(object):
def unsign(self, signed_value):
signed_value = force_str(signed_value)
if not self.sep in signed_value:
if self.sep not in signed_value:
raise BadSignature('No "%s" found in value' % self.sep)
value, sig = signed_value.rsplit(self.sep, 1)
if constant_time_compare(sig, self.signature(value)):

View File

@ -141,7 +141,7 @@ class EmailValidator(object):
if not self.user_regex.match(user_part):
raise ValidationError(self.message, code=self.code)
if (not domain_part in self.domain_whitelist and
if (domain_part not in self.domain_whitelist and
not self.validate_domain_part(domain_part)):
# Try for possible IDN domain-part
try:

View File

@ -131,7 +131,7 @@ def typecast_timestamp(s): # does NOT store time zone information
# "2005-07-29 09:56:00-05"
if not s:
return None
if not ' ' in s:
if ' ' not in s:
return typecast_date(s)
d, t = s.split()
# Extract timezone information, if it exists. Currently we just throw

View File

@ -15,7 +15,7 @@ class RegisterLookupMixin(object):
except KeyError:
# To allow for inheritance, check parent class' class_lookups.
for parent in inspect.getmro(self.__class__):
if not 'class_lookups' in parent.__dict__:
if 'class_lookups' not in parent.__dict__:
continue
if lookup_name in parent.class_lookups:
return parent.class_lookups[lookup_name]
@ -40,7 +40,7 @@ class RegisterLookupMixin(object):
@classmethod
def register_lookup(cls, lookup):
if not 'class_lookups' in cls.__dict__:
if 'class_lookups' not in cls.__dict__:
cls.class_lookups = {}
cls.class_lookups[lookup.lookup_name] = lookup

View File

@ -128,7 +128,7 @@ class BaseManager(six.with_metaclass(RenameManagerMethods)):
elif model._meta.swapped:
setattr(model, name, SwappedManagerDescriptor(model))
else:
# if not model._meta.abstract and not model._meta.swapped:
# if not model._meta.abstract and not model._meta.swapped:
setattr(model, name, ManagerDescriptor(self))
if not getattr(model, '_default_manager', None) or self.creation_counter < model._default_manager.creation_counter:
model._default_manager = self

View File

@ -153,7 +153,7 @@ class BaseFormSet(object):
if self.is_bound:
defaults['data'] = self.data
defaults['files'] = self.files
if self.initial and not 'initial' in kwargs:
if self.initial and 'initial' not in kwargs:
try:
defaults['initial'] = self.initial[i]
except IndexError:

View File

@ -46,7 +46,7 @@ def construct_instance(form, instance, fields=None, exclude=None):
file_field_list = []
for f in opts.fields:
if not f.editable or isinstance(f, models.AutoField) \
or not f.name in cleaned_data:
or f.name not in cleaned_data:
continue
if fields is not None and f.name not in fields:
continue
@ -130,7 +130,7 @@ def model_to_dict(instance, fields=None, exclude=None):
for f in opts.concrete_fields + opts.virtual_fields + opts.many_to_many:
if not getattr(f, 'editable', False):
continue
if fields and not f.name in fields:
if fields and f.name not in fields:
continue
if exclude and f.name in exclude:
continue
@ -189,7 +189,7 @@ def fields_for_model(model, fields=None, exclude=None, widgets=None,
for f in sorted(opts.concrete_fields + sortable_virtual_fields + opts.many_to_many):
if not getattr(f, 'editable', False):
continue
if fields is not None and not f.name in fields:
if fields is not None and f.name not in fields:
continue
if exclude and f.name in exclude:
continue
@ -663,7 +663,7 @@ class BaseModelFormSet(BaseFormSet):
# Reduce Model instances to their primary key values
row_data = tuple(d._get_pk_val() if hasattr(d, '_get_pk_val') else d
for d in row_data)
if row_data and not None in row_data:
if row_data and None not in row_data:
# if we've already seen it then we have a uniqueness failure
if row_data in seen_data:
# poke error messages into the right places and mark

View File

@ -132,7 +132,7 @@ class FetchFromCacheMiddleware(object):
Checks whether the page is already cached and returns the cached
version if available.
"""
if not request.method in ('GET', 'HEAD'):
if request.method not in ('GET', 'HEAD'):
request._cache_update_cache = False
return None # Don't bother checking the cache.

View File

@ -932,7 +932,7 @@ def pluralize(value, arg='s'):
* If value is 1, cand{{ value|pluralize:"y,ies" }} displays "1 candy".
* If value is 2, cand{{ value|pluralize:"y,ies" }} displays "2 candies".
"""
if not ',' in arg:
if ',' not in arg:
arg = ',' + arg
bits = arg.split(',')
if len(bits) > 2:

View File

@ -619,7 +619,7 @@ def cycle(parser, token, escape=False):
name = args[1]
if not hasattr(parser, '_namedCycleNodes'):
raise TemplateSyntaxError("No named cycles in template. '%s' is not defined" % name)
if not name in parser._namedCycleNodes:
if name not in parser._namedCycleNodes:
raise TemplateSyntaxError("Named cycle '%s' does not exist" % name)
return parser._namedCycleNodes[name]

View File

@ -276,7 +276,7 @@ def urlize(text, trim_url_limit=None, nofollow=False, autoescape=False):
url = smart_urlquote(middle)
elif simple_url_2_re.match(middle):
url = smart_urlquote('http://%s' % middle)
elif not ':' in middle and simple_email_re.match(middle):
elif ':' not in middle and simple_email_re.match(middle):
local, domain = middle.rsplit('@', 1)
try:
domain = domain.encode('idna').decode('ascii')

View File

@ -74,7 +74,7 @@ def configure_logging(logging_config, logging_settings):
warnings.simplefilter("default", RemovedInNextVersionWarning)
if logging_config:
# First find the logging configuration function ...
# First find the logging configuration function ...
logging_config_func = import_string(logging_config)
logging_config_func(DEFAULT_LOGGING)

View File

@ -115,7 +115,7 @@ def lang_stats(resources=None, languages=None):
print("\nShowing translations stats for '%s':" % name)
langs = sorted([d for d in os.listdir(dir_) if not d.startswith('_')])
for lang in langs:
if languages and not lang in languages:
if languages and lang not in languages:
continue
# TODO: merge first with the latest en catalog
p = Popen("msgfmt -vc -o /dev/null %(path)s/%(lang)s/LC_MESSAGES/django%(ext)s.po" % {

View File

@ -1414,7 +1414,7 @@ class AdminViewPermissionsTest(TestCase):
self.client.get('/test_admin/admin/')
self.client.post(login_url, self.deleteuser_login)
response = self.client.get('/test_admin/admin/admin_views/section/1/delete/')
# test response contains link to related Article
# test response contains link to related Article
self.assertContains(response, "admin_views/article/1/")
response = self.client.get('/test_admin/admin/admin_views/article/1/delete/')

View File

@ -1161,7 +1161,7 @@ class FieldsTests(SimpleTestCase):
"'Select a valid choice. 3 is not one of the available choices.'",
f.clean, ['3'])
# ComboField ##################################################################
# ComboField ##################################################################
def test_combofield_1(self):
f = ComboField(fields=[CharField(max_length=20), EmailField()])

View File

@ -436,7 +436,7 @@ class LookupTests(TestCase):
])
def test_none(self):
# none() returns a QuerySet that behaves like any other QuerySet object
# none() returns a QuerySet that behaves like any other QuerySet object
self.assertQuerysetEqual(Article.objects.none(), [])
self.assertQuerysetEqual(
Article.objects.none().filter(headline__startswith='Article'), [])

View File

@ -192,7 +192,7 @@ class MailTests(HeadersCheckMixin, SimpleTestCase):
SafeMIMEMultipart as well
"""
headers = {"Date": "Fri, 09 Nov 2001 01:08:47 -0000", "Message-ID": "foo"}
subject, from_email, to = 'hello', 'from@example.com', '"Sürname, Firstname" <to@example.com>'
from_email, to = 'from@example.com', '"Sürname, Firstname" <to@example.com>'
text_content = 'This is an important message.'
html_content = '<p>This is an <strong>important</strong> message.</p>'
msg = EmailMultiAlternatives('Message from Firstname Sürname', text_content, from_email, [to], headers=headers)

View File

@ -24,7 +24,7 @@ class Person(models.Model):
def save(self, *args, **kwargs):
self.data.append("Before save")
# Call the "real" save() method
# Call the "real" save() method
super(Person, self).save(*args, **kwargs)
self.data.append("After save")

View File

@ -1,4 +1,4 @@
# -*- coding: utf-8 -*-
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import datetime

View File

@ -259,7 +259,8 @@ class TemplateResponseTest(TestCase):
'first/test.html', {
'value': 123,
'fn': datetime.now,
})
}
)
self.assertRaises(ContentNotRenderedError,
pickle.dumps, response)