Skip to content

Commit

Permalink
Fixed #26125 -- Fixed E731 flake warnings.
Browse files Browse the repository at this point in the history
  • Loading branch information
userimack authored and timgraham committed Jan 25, 2016
1 parent abc0777 commit 60586dd
Show file tree
Hide file tree
Showing 36 changed files with 176 additions and 75 deletions.
9 changes: 6 additions & 3 deletions django/conf/global_settings.py
Original file line number Diff line number Diff line change
@@ -1,12 +1,15 @@
# -*- coding: utf-8 -*-
"""
Default Django settings. Override these with settings in the module pointed to
by the DJANGO_SETTINGS_MODULE environment variable.
"""
from __future__ import unicode_literals

# Default Django settings. Override these with settings in the module
# pointed-to by the DJANGO_SETTINGS_MODULE environment variable.

# This is defined here as a do-nothing function because we can't import
# django.utils.translation -- that module depends on the settings.
gettext_noop = lambda s: s
def gettext_noop(s):
return s

####################
# CORE #
Expand Down
7 changes: 5 additions & 2 deletions django/contrib/admin/templatetags/admin_list.py
Original file line number Diff line number Diff line change
Expand Up @@ -143,7 +143,9 @@ def result_headers(cl):
o_list_primary = [] # URL for making this field the primary sort
o_list_remove = [] # URL for removing this field from sort
o_list_toggle = [] # URL for toggling order type for this field
make_qs_param = lambda t, n: ('-' if t == 'desc' else '') + str(n)

def make_qs_param(t, n):
return ('-' if t == 'desc' else '') + str(n)

for j, ot in ordering_field_columns.items():
if j == i: # Same column
Expand Down Expand Up @@ -341,7 +343,8 @@ def date_hierarchy(cl):
month_lookup = cl.params.get(month_field)
day_lookup = cl.params.get(day_field)

link = lambda filters: cl.get_query_string(filters, [field_generic])
def link(filters):
return cl.get_query_string(filters, [field_generic])

if not (year_lookup or month_lookup or day_lookup):
# select appropriate start level
Expand Down
6 changes: 4 additions & 2 deletions django/contrib/postgres/validators.py
Original file line number Diff line number Diff line change
Expand Up @@ -69,10 +69,12 @@ def __ne__(self, other):


class RangeMaxValueValidator(MaxValueValidator):
compare = lambda self, a, b: a.upper > b
def compare(self, a, b):
return a.upper > b
message = _('Ensure that this range is completely less than or equal to %(limit_value)s.')


class RangeMinValueValidator(MinValueValidator):
compare = lambda self, a, b: a.lower < b
def compare(self, a, b):
return a.lower < b
message = _('Ensure that this range is completely greater than or equal to %(limit_value)s.')
10 changes: 7 additions & 3 deletions django/contrib/staticfiles/storage.py
Original file line number Diff line number Diff line change
Expand Up @@ -217,11 +217,15 @@ def post_process(self, paths, dry_run=False, **options):
hashed_files = OrderedDict()

# build a list of adjustable files
matches = lambda path: matches_patterns(path, self._patterns.keys())
adjustable_paths = [path for path in paths if matches(path)]
adjustable_paths = [
path for path in paths
if matches_patterns(path, self._patterns.keys())
]

# then sort the files by the directory level
path_level = lambda name: len(name.split(os.sep))
def path_level(name):
return len(name.split(os.sep))

for name in sorted(paths.keys(), key=path_level, reverse=True):

# use the original, local file, not the copied-but-unprocessed
Expand Down
3 changes: 1 addition & 2 deletions django/core/cache/backends/memcached.py
Original file line number Diff line number Diff line change
Expand Up @@ -146,8 +146,7 @@ def set_many(self, data, timeout=DEFAULT_TIMEOUT, version=None):
self._cache.set_multi(safe_data, self.get_backend_timeout(timeout))

def delete_many(self, keys, version=None):
l = lambda x: self.make_key(x, version=version)
self._cache.delete_multi(map(l, keys))
self._cache.delete_multi(self.make_key(key, version=version) for key in keys)

def clear(self):
self._cache.flush_all()
Expand Down
3 changes: 2 additions & 1 deletion django/core/management/color.py
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,8 @@ def make_style(config_string=''):
format = color_settings.get(role, {})
style_func = termcolors.make_style(**format)
else:
style_func = lambda x: x
def style_func(x):
return x
setattr(style, role, style_func)

# For backwards compatibility,
Expand Down
7 changes: 5 additions & 2 deletions django/core/management/commands/inspectdb.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,8 +32,11 @@ def handle_inspection(self, options):
# 'table_name_filter' is a stealth option
table_name_filter = options.get('table_name_filter')

table2model = lambda table_name: re.sub(r'[^a-zA-Z0-9]', '', table_name.title())
strip_prefix = lambda s: s[1:] if s.startswith("u'") else s
def table2model(table_name):
return re.sub(r'[^a-zA-Z0-9]', '', table_name.title())

def strip_prefix(s):
return s[1:] if s.startswith("u'") else s

with connection.cursor() as cursor:
yield "# This is an auto-generated Django model module."
Expand Down
6 changes: 4 additions & 2 deletions django/core/management/commands/makemessages.py
Original file line number Diff line number Diff line change
Expand Up @@ -365,8 +365,10 @@ def is_ignored(path, ignore_patterns):
Check if the given path should be ignored or not.
"""
filename = os.path.basename(path)
ignore = lambda pattern: (fnmatch.fnmatchcase(filename, pattern) or
fnmatch.fnmatchcase(path, pattern))

def ignore(pattern):
return fnmatch.fnmatchcase(filename, pattern) or fnmatch.fnmatchcase(path, pattern)

return any(ignore(pattern) for pattern in ignore_patterns)

ignore_patterns = [os.path.normcase(p) for p in self.ignore_patterns]
Expand Down
5 changes: 4 additions & 1 deletion django/core/management/commands/makemigrations.py
Original file line number Diff line number Diff line change
Expand Up @@ -224,7 +224,10 @@ def handle_merge(self, loader, conflicts):
if mig[0] == migration.app_label
]
merge_migrations.append(migration)
all_items_equal = lambda seq: all(item == seq[0] for item in seq[1:])

def all_items_equal(seq):
return all(item == seq[0] for item in seq[1:])

merge_migrations_generations = zip(*[m.ancestry for m in merge_migrations])
common_ancestor_count = sum(1 for common_ancestor_generation
in takewhile(all_items_equal, merge_migrations_generations))
Expand Down
9 changes: 6 additions & 3 deletions django/core/serializers/python.py
Original file line number Diff line number Diff line change
Expand Up @@ -70,9 +70,11 @@ def handle_fk_field(self, obj, field):
def handle_m2m_field(self, obj, field):
if field.remote_field.through._meta.auto_created:
if self.use_natural_foreign_keys and hasattr(field.remote_field.model, 'natural_key'):
m2m_value = lambda value: value.natural_key()
def m2m_value(value):
return value.natural_key()
else:
m2m_value = lambda value: force_text(value._get_pk_val(), strings_only=True)
def m2m_value(value):
return force_text(value._get_pk_val(), strings_only=True)
self._current[field.name] = [m2m_value(related)
for related in getattr(obj, field.name).iterator()]

Expand Down Expand Up @@ -136,7 +138,8 @@ def m2m_convert(value):
else:
return force_text(model._meta.pk.to_python(value), strings_only=True)
else:
m2m_convert = lambda v: force_text(model._meta.pk.to_python(v), strings_only=True)
def m2m_convert(v):
return force_text(model._meta.pk.to_python(v), strings_only=True)

try:
m2m_data[field.name] = []
Expand Down
3 changes: 2 additions & 1 deletion django/core/serializers/xml_serializer.py
Original file line number Diff line number Diff line change
Expand Up @@ -275,7 +275,8 @@ def m2m_convert(n):
obj_pk = model._meta.pk.to_python(n.getAttribute('pk'))
return obj_pk
else:
m2m_convert = lambda n: model._meta.pk.to_python(n.getAttribute('pk'))
def m2m_convert(n):
return model._meta.pk.to_python(n.getAttribute('pk'))
return [m2m_convert(c) for c in node.getElementsByTagName("object")]

def _get_model_from_node(self, node, attr):
Expand Down
32 changes: 24 additions & 8 deletions django/core/validators.py
Original file line number Diff line number Diff line change
Expand Up @@ -295,8 +295,6 @@ def int_list_validator(sep=',', message=None, code='invalid'):

@deconstructible
class BaseValidator(object):
compare = lambda self, a, b: a is not b
clean = lambda self, x: x
message = _('Ensure this value is %(limit_value)s (it is %(show_value)s).')
code = 'limit_value'

Expand All @@ -319,42 +317,60 @@ def __eq__(self, other):
and (self.code == other.code)
)

def compare(self, a, b):
return a is not b

def clean(self, x):
return x


@deconstructible
class MaxValueValidator(BaseValidator):
compare = lambda self, a, b: a > b
message = _('Ensure this value is less than or equal to %(limit_value)s.')
code = 'max_value'

def compare(self, a, b):
return a > b


@deconstructible
class MinValueValidator(BaseValidator):
compare = lambda self, a, b: a < b
message = _('Ensure this value is greater than or equal to %(limit_value)s.')
code = 'min_value'

def compare(self, a, b):
return a < b


@deconstructible
class MinLengthValidator(BaseValidator):
compare = lambda self, a, b: a < b
clean = lambda self, x: len(x)
message = ungettext_lazy(
'Ensure this value has at least %(limit_value)d character (it has %(show_value)d).',
'Ensure this value has at least %(limit_value)d characters (it has %(show_value)d).',
'limit_value')
code = 'min_length'

def compare(self, a, b):
return a < b

def clean(self, x):
return len(x)


@deconstructible
class MaxLengthValidator(BaseValidator):
compare = lambda self, a, b: a > b
clean = lambda self, x: len(x)
message = ungettext_lazy(
'Ensure this value has at most %(limit_value)d character (it has %(show_value)d).',
'Ensure this value has at most %(limit_value)d characters (it has %(show_value)d).',
'limit_value')
code = 'max_length'

def compare(self, a, b):
return a > b

def clean(self, x):
return len(x)


@deconstructible
class DecimalValidator(object):
Expand Down
3 changes: 2 additions & 1 deletion django/db/backends/base/operations.py
Original file line number Diff line number Diff line change
Expand Up @@ -204,7 +204,8 @@ def last_executed_query(self, cursor, sql, params):
according to their own quoting schemes.
"""
# Convert params to contain Unicode values.
to_unicode = lambda s: force_text(s, strings_only=True, errors='replace')
def to_unicode(s):
return force_text(s, strings_only=True, errors='replace')
if isinstance(params, (list, tuple)):
u_params = tuple(to_unicode(val) for val in params)
elif params is None:
Expand Down
5 changes: 4 additions & 1 deletion django/db/backends/mysql/introspection.py
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,10 @@ def get_table_description(self, cursor, table_name):
field_info = {line[0]: InfoLine(*line) for line in cursor.fetchall()}

cursor.execute("SELECT * FROM %s LIMIT 1" % self.connection.ops.quote_name(table_name))
to_int = lambda i: int(i) if i is not None else i

def to_int(i):
return int(i) if i is not None else i

fields = []
for line in cursor.description:
col_name = force_text(line[0])
Expand Down
5 changes: 4 additions & 1 deletion django/db/models/fields/related.py
Original file line number Diff line number Diff line change
Expand Up @@ -85,7 +85,10 @@ def add_lazy_relation(cls, field, relation, operation):
"and related methods on the Apps class.",
RemovedInDjango20Warning, stacklevel=2)
# Rearrange args for new Apps.lazy_model_operation
function = lambda local, related, field: operation(field, related, local)

def function(local, related, field):
return operation(field, related, local)

lazy_related_operation(function, cls, relation, field=field)


Expand Down
5 changes: 4 additions & 1 deletion django/db/models/fields/related_descriptors.py
Original file line number Diff line number Diff line change
Expand Up @@ -300,7 +300,10 @@ def get_prefetch_queryset(self, instances, queryset=None):
queryset._add_hints(instance=instances[0])

rel_obj_attr = attrgetter(self.related.field.attname)
instance_attr = lambda obj: obj._get_pk_val()

def instance_attr(obj):
return obj._get_pk_val()

instances_dict = {instance_attr(inst): inst for inst in instances}
query = {'%s__in' % self.related.field.name: instances}
queryset = queryset.filter(**query)
Expand Down
16 changes: 11 additions & 5 deletions django/db/models/options.py
Original file line number Diff line number Diff line change
Expand Up @@ -371,11 +371,17 @@ def fields(self):
# use that property directly because related_model is a cached property,
# and all the models may not have been loaded yet; we don't want to cache
# the string reference to the related_model.
is_not_an_m2m_field = lambda f: not (f.is_relation and f.many_to_many)
is_not_a_generic_relation = lambda f: not (f.is_relation and f.one_to_many)
is_not_a_generic_foreign_key = lambda f: not (
f.is_relation and f.many_to_one and not (hasattr(f.remote_field, 'model') and f.remote_field.model)
)
def is_not_an_m2m_field(f):
return not (f.is_relation and f.many_to_many)

def is_not_a_generic_relation(f):
return not (f.is_relation and f.one_to_many)

def is_not_a_generic_foreign_key(f):
return not (
f.is_relation and f.many_to_one and not (hasattr(f.remote_field, 'model') and f.remote_field.model)
)

return make_immutable_fields_list(
"fields",
(f for f in self._get_fields(reverse=False) if
Expand Down
7 changes: 5 additions & 2 deletions django/http/request.py
Original file line number Diff line number Diff line change
Expand Up @@ -481,9 +481,12 @@ def urlencode(self, safe=None):
output = []
if safe:
safe = force_bytes(safe, self.encoding)
encode = lambda k, v: '%s=%s' % ((quote(k, safe), quote(v, safe)))

def encode(k, v):
return '%s=%s' % ((quote(k, safe), quote(v, safe)))
else:
encode = lambda k, v: urlencode({k: v})
def encode(k, v):
return urlencode({k: v})
for k, list_ in self.lists():
k = force_bytes(k, self.encoding)
output.extend(encode(k, force_bytes(v, self.encoding))
Expand Down
6 changes: 4 additions & 2 deletions django/template/defaultfilters.py
Original file line number Diff line number Diff line change
Expand Up @@ -639,7 +639,8 @@ def unordered_list(value, autoescape=True):
if autoescape:
escaper = conditional_escape
else:
escaper = lambda x: x
def escaper(x):
return x

def walk_items(item_list):
item_iterator = iter(item_list)
Expand Down Expand Up @@ -850,7 +851,8 @@ def filesizeformat(bytes_):
value = ungettext("%(size)d byte", "%(size)d bytes", 0) % {'size': 0}
return avoid_wrapping(value)

filesize_number_format = lambda value: formats.number_format(round(value, 1), 1)
def filesize_number_format(value):
return formats.number_format(round(value, 1), 1)

KB = 1 << 10
MB = 1 << 20
Expand Down
10 changes: 7 additions & 3 deletions django/test/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -160,10 +160,13 @@ def encode_multipart(boundary, data):
as an application/octet-stream; otherwise, str(value) will be sent.
"""
lines = []
to_bytes = lambda s: force_bytes(s, settings.DEFAULT_CHARSET)

def to_bytes(s):
return force_bytes(s, settings.DEFAULT_CHARSET)

# Not by any means perfect, but good enough for our purposes.
is_file = lambda thing: hasattr(thing, "read") and callable(thing.read)
def is_file(thing):
return hasattr(thing, "read") and callable(thing.read)

# Each bit of the multipart form data could be either a form value or a
# file, or a *list* of form values and/or files. Remember that HTTP field
Expand Down Expand Up @@ -198,7 +201,8 @@ def encode_multipart(boundary, data):


def encode_file(boundary, key, file):
to_bytes = lambda s: force_bytes(s, settings.DEFAULT_CHARSET)
def to_bytes(s):
return force_bytes(s, settings.DEFAULT_CHARSET)
filename = os.path.basename(file.name) if hasattr(file, 'name') else ''
if hasattr(file, 'content_type'):
content_type = file.content_type
Expand Down
3 changes: 2 additions & 1 deletion django/utils/decorators.py
Original file line number Diff line number Diff line change
Expand Up @@ -159,7 +159,8 @@ def _wrapped_view(request, *args, **kwargs):
# Defer running of process_response until after the template
# has been rendered:
if hasattr(middleware, 'process_response'):
callback = lambda response: middleware.process_response(request, response)
def callback(response):
return middleware.process_response(request, response)
response.add_post_render_callback(callback)
else:
if hasattr(middleware, 'process_response'):
Expand Down
Loading

0 comments on commit 60586dd

Please sign in to comment.