Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse files

Eliminated lots of mutable default arguments (since they are bugs

waiting to happen and are memory leaks too).


git-svn-id: http://code.djangoproject.com/svn/django/trunk@3070 bcc190cf-cafb-0310-a4f2-bffc1f526a37
  • Loading branch information...
commit 9b86db9bf2407f408468566b3f48a8444cb66f83 1 parent 88d215f
@spookylukey spookylukey authored
View
8 django/contrib/admin/utils.py
@@ -81,12 +81,16 @@ def parse_rst(text, default_reference_context, thing_being_parsed=None, link_bas
}
def create_reference_role(rolename, urlbase):
- def _role(name, rawtext, text, lineno, inliner, options={}, content=[]):
+ def _role(name, rawtext, text, lineno, inliner, options=None, content=None):
+ if options is None: options = {}
+ if content is None: content = []
node = docutils.nodes.reference(rawtext, text, refuri=(urlbase % (inliner.document.settings.link_base, text.lower())), **options)
return [node], []
docutils.parsers.rst.roles.register_canonical_role(rolename, _role)
-def default_reference_role(name, rawtext, text, lineno, inliner, options={}, content=[]):
+def default_reference_role(name, rawtext, text, lineno, inliner, options=None, content=None):
+ if options is None: options = {}
+ if content is None: content = []
context = inliner.document.settings.default_reference_context
node = docutils.nodes.reference(rawtext, text, refuri=(ROLES[context] % (inliner.document.settings.link_base, text.lower())), **options)
return [node], []
View
4 django/contrib/admin/views/main.py
@@ -579,7 +579,9 @@ def get_filters(self, request):
filter_specs.append(spec)
return filter_specs, bool(filter_specs)
- def get_query_string(self, new_params={}, remove=[]):
+ def get_query_string(self, new_params=None, remove=None):
+ if new_params is None: new_params = {}
+ if remove is None: remove = []
p = self.params.copy()
for r in remove:
for k in p.keys():
View
3  django/core/validators.py
@@ -399,7 +399,8 @@ class AnyValidator:
as a validation error. The message is rather unspecific, so it's best to
specify one on instantiation.
"""
- def __init__(self, validator_list=[], error_message=gettext_lazy("This field is invalid.")):
+ def __init__(self, validator_list=None, error_message=gettext_lazy("This field is invalid.")):
+ if validator_list is None: validator_list = []
self.validator_list = validator_list
self.error_message = error_message
for v in validator_list:
View
6 django/db/backends/oracle/base.py
@@ -65,11 +65,13 @@ class FormatStylePlaceholderCursor(Database.Cursor):
This fixes it -- but note that if you want to use a literal "%s" in a query,
you'll need to use "%%s".
"""
- def execute(self, query, params=[]):
+ def execute(self, query, params=None):
+ if params is None: params = []
query = self.convert_arguments(query, len(params))
return Database.Cursor.execute(self, query, params)
- def executemany(self, query, params=[]):
+ def executemany(self, query, params=None):
+ if params is None: params = []
query = self.convert_arguments(query, len(params[0]))
return Database.Cursor.executemany(self, query, params)
View
71 django/forms/__init__.py
@@ -367,7 +367,8 @@ def get_id(self):
class TextField(FormField):
input_type = "text"
- def __init__(self, field_name, length=30, maxlength=None, is_required=False, validator_list=[], member_name=None):
+ def __init__(self, field_name, length=30, maxlength=None, is_required=False, validator_list=None, member_name=None):
+ if validator_list is None: validator_list = []
self.field_name = field_name
self.length, self.maxlength = length, maxlength
self.is_required = is_required
@@ -404,7 +405,8 @@ class PasswordField(TextField):
input_type = "password"
class LargeTextField(TextField):
- def __init__(self, field_name, rows=10, cols=40, is_required=False, validator_list=[], maxlength=None):
+ def __init__(self, field_name, rows=10, cols=40, is_required=False, validator_list=None, maxlength=None):
+ if validator_list is None: validator_list = []
self.field_name = field_name
self.rows, self.cols, self.is_required = rows, cols, is_required
self.validator_list = validator_list[:]
@@ -422,7 +424,8 @@ def render(self, data):
self.field_name, self.rows, self.cols, escape(data))
class HiddenField(FormField):
- def __init__(self, field_name, is_required=False, validator_list=[]):
+ def __init__(self, field_name, is_required=False, validator_list=None):
+ if validator_list is None: validator_list = []
self.field_name, self.is_required = field_name, is_required
self.validator_list = validator_list[:]
@@ -452,7 +455,9 @@ def html2python(data):
html2python = staticmethod(html2python)
class SelectField(FormField):
- def __init__(self, field_name, choices=[], size=1, is_required=False, validator_list=[], member_name=None):
+ def __init__(self, field_name, choices=None, size=1, is_required=False, validator_list=None, member_name=None):
+ if validator_list is None: validator_list = []
+ if choices is None: choices = []
self.field_name = field_name
# choices is a list of (value, human-readable key) tuples because order matters
self.choices, self.size, self.is_required = choices, size, is_required
@@ -488,7 +493,9 @@ def html2python(data):
html2python = staticmethod(html2python)
class RadioSelectField(FormField):
- def __init__(self, field_name, choices=[], ul_class='', is_required=False, validator_list=[], member_name=None):
+ def __init__(self, field_name, choices=None, ul_class='', is_required=False, validator_list=None, member_name=None):
+ if validator_list is None: validator_list = []
+ if choices is None: choices = []
self.field_name = field_name
# choices is a list of (value, human-readable key) tuples because order matters
self.choices, self.is_required = choices, is_required
@@ -552,7 +559,8 @@ def isValidChoice(self, data, form):
class NullBooleanField(SelectField):
"This SelectField provides 'Yes', 'No' and 'Unknown', mapping results to True, False or None"
- def __init__(self, field_name, is_required=False, validator_list=[]):
+ def __init__(self, field_name, is_required=False, validator_list=None):
+ if validator_list is None: validator_list = []
SelectField.__init__(self, field_name, choices=[('1', 'Unknown'), ('2', 'Yes'), ('3', 'No')],
is_required=is_required, validator_list=validator_list)
@@ -605,7 +613,9 @@ class CheckboxSelectMultipleField(SelectMultipleField):
back into the single list that validators, renderers and save() expect.
"""
requires_data_list = True
- def __init__(self, field_name, choices=[], validator_list=[]):
+ def __init__(self, field_name, choices=None, validator_list=None):
+ if validator_list is None: validator_list = []
+ if choices is None: choices = []
SelectMultipleField.__init__(self, field_name, choices, size=1, is_required=False, validator_list=validator_list)
def prepare(self, new_data):
@@ -636,7 +646,8 @@ def render(self, data):
####################
class FileUploadField(FormField):
- def __init__(self, field_name, is_required=False, validator_list=[]):
+ def __init__(self, field_name, is_required=False, validator_list=None):
+ if validator_list is None: validator_list = []
self.field_name, self.is_required = field_name, is_required
self.validator_list = [self.isNonEmptyFile] + validator_list
@@ -675,7 +686,8 @@ def isValidImage(self, field_data, all_data):
####################
class IntegerField(TextField):
- def __init__(self, field_name, length=10, maxlength=None, is_required=False, validator_list=[], member_name=None):
+ def __init__(self, field_name, length=10, maxlength=None, is_required=False, validator_list=None, member_name=None):
+ if validator_list is None: validator_list = []
validator_list = [self.isInteger] + validator_list
if member_name is not None:
self.member_name = member_name
@@ -694,7 +706,8 @@ def html2python(data):
html2python = staticmethod(html2python)
class SmallIntegerField(IntegerField):
- def __init__(self, field_name, length=5, maxlength=5, is_required=False, validator_list=[]):
+ def __init__(self, field_name, length=5, maxlength=5, is_required=False, validator_list=None):
+ if validator_list is None: validator_list = []
validator_list = [self.isSmallInteger] + validator_list
IntegerField.__init__(self, field_name, length, maxlength, is_required, validator_list)
@@ -703,7 +716,8 @@ def isSmallInteger(self, field_data, all_data):
raise validators.CriticalValidationError, gettext("Enter a whole number between -32,768 and 32,767.")
class PositiveIntegerField(IntegerField):
- def __init__(self, field_name, length=10, maxlength=None, is_required=False, validator_list=[]):
+ def __init__(self, field_name, length=10, maxlength=None, is_required=False, validator_list=None):
+ if validator_list is None: validator_list = []
validator_list = [self.isPositive] + validator_list
IntegerField.__init__(self, field_name, length, maxlength, is_required, validator_list)
@@ -712,7 +726,8 @@ def isPositive(self, field_data, all_data):
raise validators.CriticalValidationError, gettext("Enter a positive number.")
class PositiveSmallIntegerField(IntegerField):
- def __init__(self, field_name, length=5, maxlength=None, is_required=False, validator_list=[]):
+ def __init__(self, field_name, length=5, maxlength=None, is_required=False, validator_list=None):
+ if validator_list is None: validator_list = []
validator_list = [self.isPositiveSmall] + validator_list
IntegerField.__init__(self, field_name, length, maxlength, is_required, validator_list)
@@ -721,7 +736,8 @@ def isPositiveSmall(self, field_data, all_data):
raise validators.CriticalValidationError, gettext("Enter a whole number between 0 and 32,767.")
class FloatField(TextField):
- def __init__(self, field_name, max_digits, decimal_places, is_required=False, validator_list=[]):
+ def __init__(self, field_name, max_digits, decimal_places, is_required=False, validator_list=None):
+ if validator_list is None: validator_list = []
self.max_digits, self.decimal_places = max_digits, decimal_places
validator_list = [self.isValidFloat] + validator_list
TextField.__init__(self, field_name, max_digits+1, max_digits+1, is_required, validator_list)
@@ -746,7 +762,8 @@ def html2python(data):
class DatetimeField(TextField):
"""A FormField that automatically converts its data to a datetime.datetime object.
The data should be in the format YYYY-MM-DD HH:MM:SS."""
- def __init__(self, field_name, length=30, maxlength=None, is_required=False, validator_list=[]):
+ def __init__(self, field_name, length=30, maxlength=None, is_required=False, validator_list=None):
+ if validator_list is None: validator_list = []
self.field_name = field_name
self.length, self.maxlength = length, maxlength
self.is_required = is_required
@@ -769,7 +786,8 @@ def html2python(data):
class DateField(TextField):
"""A FormField that automatically converts its data to a datetime.date object.
The data should be in the format YYYY-MM-DD."""
- def __init__(self, field_name, is_required=False, validator_list=[]):
+ def __init__(self, field_name, is_required=False, validator_list=None):
+ if validator_list is None: validator_list = []
validator_list = [self.isValidDate] + validator_list
TextField.__init__(self, field_name, length=10, maxlength=10,
is_required=is_required, validator_list=validator_list)
@@ -793,7 +811,8 @@ def html2python(data):
class TimeField(TextField):
"""A FormField that automatically converts its data to a datetime.time object.
The data should be in the format HH:MM:SS or HH:MM:SS.mmmmmm."""
- def __init__(self, field_name, is_required=False, validator_list=[]):
+ def __init__(self, field_name, is_required=False, validator_list=None):
+ if validator_list is None: validator_list = []
validator_list = [self.isValidTime] + validator_list
TextField.__init__(self, field_name, length=8, maxlength=8,
is_required=is_required, validator_list=validator_list)
@@ -827,7 +846,8 @@ def html2python(data):
class EmailField(TextField):
"A convenience FormField for validating e-mail addresses"
- def __init__(self, field_name, length=50, maxlength=75, is_required=False, validator_list=[]):
+ def __init__(self, field_name, length=50, maxlength=75, is_required=False, validator_list=None):
+ if validator_list is None: validator_list = []
validator_list = [self.isValidEmail] + validator_list
TextField.__init__(self, field_name, length, maxlength=maxlength,
is_required=is_required, validator_list=validator_list)
@@ -840,7 +860,8 @@ def isValidEmail(self, field_data, all_data):
class URLField(TextField):
"A convenience FormField for validating URLs"
- def __init__(self, field_name, length=50, maxlength=200, is_required=False, validator_list=[]):
+ def __init__(self, field_name, length=50, maxlength=200, is_required=False, validator_list=None):
+ if validator_list is None: validator_list = []
validator_list = [self.isValidURL] + validator_list
TextField.__init__(self, field_name, length=length, maxlength=maxlength,
is_required=is_required, validator_list=validator_list)
@@ -852,7 +873,8 @@ def isValidURL(self, field_data, all_data):
raise validators.CriticalValidationError, e.messages
class IPAddressField(TextField):
- def __init__(self, field_name, length=15, maxlength=15, is_required=False, validator_list=[]):
+ def __init__(self, field_name, length=15, maxlength=15, is_required=False, validator_list=None):
+ if validator_list is None: validator_list = []
validator_list = [self.isValidIPAddress] + validator_list
TextField.__init__(self, field_name, length=length, maxlength=maxlength,
is_required=is_required, validator_list=validator_list)
@@ -873,7 +895,7 @@ def html2python(data):
class FilePathField(SelectField):
"A SelectField whose choices are the files in a given directory."
- def __init__(self, field_name, path, match=None, recursive=False, is_required=False, validator_list=[]):
+ def __init__(self, field_name, path, match=None, recursive=False, is_required=False, validator_list=None):
import os
if match is not None:
import re
@@ -896,7 +918,8 @@ def __init__(self, field_name, path, match=None, recursive=False, is_required=Fa
class PhoneNumberField(TextField):
"A convenience FormField for validating phone numbers (e.g. '630-555-1234')"
- def __init__(self, field_name, is_required=False, validator_list=[]):
+ def __init__(self, field_name, is_required=False, validator_list=None):
+ if validator_list is None: validator_list = []
validator_list = [self.isValidPhone] + validator_list
TextField.__init__(self, field_name, length=12, maxlength=12,
is_required=is_required, validator_list=validator_list)
@@ -909,7 +932,8 @@ def isValidPhone(self, field_data, all_data):
class USStateField(TextField):
"A convenience FormField for validating U.S. states (e.g. 'IL')"
- def __init__(self, field_name, is_required=False, validator_list=[]):
+ def __init__(self, field_name, is_required=False, validator_list=None):
+ if validator_list is None: validator_list = []
validator_list = [self.isValidUSState] + validator_list
TextField.__init__(self, field_name, length=2, maxlength=2,
is_required=is_required, validator_list=validator_list)
@@ -929,7 +953,8 @@ def html2python(data):
class CommaSeparatedIntegerField(TextField):
"A convenience FormField for validating comma-separated integer fields"
- def __init__(self, field_name, maxlength=None, is_required=False, validator_list=[]):
+ def __init__(self, field_name, maxlength=None, is_required=False, validator_list=None):
+ if validator_list is None: validator_list = []
validator_list = [self.isCommaSeparatedIntegerList] + validator_list
TextField.__init__(self, field_name, length=20, maxlength=maxlength,
is_required=is_required, validator_list=validator_list)
View
3  django/template/__init__.py
@@ -227,7 +227,8 @@ def __init__(self, tokens):
for lib in builtins:
self.add_library(lib)
- def parse(self, parse_until=[]):
+ def parse(self, parse_until=None):
+ if parse_until is None: parse_until = []
nodelist = self.create_nodelist()
while self.tokens:
token = self.next_token()
View
5 django/utils/datastructures.py
@@ -42,7 +42,8 @@ def has_key(self, key):
class SortedDict(dict):
"A dictionary that keeps its keys in the order in which they're inserted."
- def __init__(self, data={}):
+ def __init__(self, data=None):
+ if data is None: data = {}
dict.__init__(self, data)
self.keyOrder = data.keys()
@@ -123,7 +124,7 @@ def __setitem__(self, key, value):
def __copy__(self):
return self.__class__(dict.items(self))
- def __deepcopy__(self, memo={}):
+ def __deepcopy__(self, memo):
import copy
result = self.__class__()
memo[id(self)] = result
View
3  django/utils/xmlutils.py
@@ -5,8 +5,9 @@
from xml.sax.saxutils import XMLGenerator
class SimplerXMLGenerator(XMLGenerator):
- def addQuickElement(self, name, contents=None, attrs={}):
+ def addQuickElement(self, name, contents=None, attrs=None):
"Convenience method for adding an element with no children"
+ if attrs is None: attrs = {}
self.startElement(name, attrs)
if contents is not None:
self.characters(contents)
View
9 django/views/generic/create_update.py
@@ -9,7 +9,7 @@
from django.core.exceptions import ObjectDoesNotExist, ImproperlyConfigured
def create_object(request, model, template_name=None,
- template_loader=loader, extra_context={}, post_save_redirect=None,
+ template_loader=loader, extra_context=None, post_save_redirect=None,
login_required=False, follow=None, context_processors=None):
"""
Generic object-creation function.
@@ -19,6 +19,7 @@ def create_object(request, model, template_name=None,
form
the form wrapper for the object
"""
+ if extra_context is None: extra_context = {}
if login_required and request.user.is_anonymous():
return redirect_to_login(request.path)
@@ -71,7 +72,7 @@ def create_object(request, model, template_name=None,
def update_object(request, model, object_id=None, slug=None,
slug_field=None, template_name=None, template_loader=loader,
- extra_context={}, post_save_redirect=None,
+ extra_context=None, post_save_redirect=None,
login_required=False, follow=None, context_processors=None,
template_object_name='object'):
"""
@@ -84,6 +85,7 @@ def update_object(request, model, object_id=None, slug=None,
object
the original object being edited
"""
+ if extra_context is None: extra_context = {}
if login_required and request.user.is_anonymous():
return redirect_to_login(request.path)
@@ -143,7 +145,7 @@ def update_object(request, model, object_id=None, slug=None,
def delete_object(request, model, post_delete_redirect,
object_id=None, slug=None, slug_field=None, template_name=None,
- template_loader=loader, extra_context={},
+ template_loader=loader, extra_context=None,
login_required=False, context_processors=None, template_object_name='object'):
"""
Generic object-delete function.
@@ -157,6 +159,7 @@ def delete_object(request, model, post_delete_redirect,
object
the original object being deleted
"""
+ if extra_context is None: extra_context = {}
if login_required and request.user.is_anonymous():
return redirect_to_login(request.path)
View
18 django/views/generic/date_based.py
@@ -6,7 +6,7 @@
def archive_index(request, queryset, date_field, num_latest=15,
template_name=None, template_loader=loader,
- extra_context={}, allow_empty=False, context_processors=None,
+ extra_context=None, allow_empty=False, context_processors=None,
mimetype=None):
"""
Generic top-level archive of date-based objects.
@@ -18,6 +18,7 @@ def archive_index(request, queryset, date_field, num_latest=15,
latest
Latest N (defaults to 15) objects by date
"""
+ if extra_context is None: extra_context = {}
model = queryset.model
queryset = queryset.filter(**{'%s__lte' % date_field: datetime.datetime.now()})
date_list = queryset.dates(date_field, 'year')[::-1]
@@ -44,7 +45,7 @@ def archive_index(request, queryset, date_field, num_latest=15,
return HttpResponse(t.render(c), mimetype=mimetype)
def archive_year(request, year, queryset, date_field, template_name=None,
- template_loader=loader, extra_context={}, allow_empty=False,
+ template_loader=loader, extra_context=None, allow_empty=False,
context_processors=None, template_object_name='object', mimetype=None,
make_object_list=False):
"""
@@ -60,6 +61,7 @@ def archive_year(request, year, queryset, date_field, template_name=None,
List of objects published in the given month
(Only available if make_object_list argument is True)
"""
+ if extra_context is None: extra_context = {}
model = queryset.model
now = datetime.datetime.now()
@@ -92,7 +94,7 @@ def archive_year(request, year, queryset, date_field, template_name=None,
def archive_month(request, year, month, queryset, date_field,
month_format='%b', template_name=None, template_loader=loader,
- extra_context={}, allow_empty=False, context_processors=None,
+ extra_context=None, allow_empty=False, context_processors=None,
template_object_name='object', mimetype=None):
"""
Generic monthly archive view.
@@ -108,6 +110,7 @@ def archive_month(request, year, month, queryset, date_field,
object_list:
list of objects published in the given month
"""
+ if extra_context is None: extra_context = {}
try:
date = datetime.date(*time.strptime(year+month, '%Y'+month_format)[:3])
except ValueError:
@@ -148,7 +151,7 @@ def archive_month(request, year, month, queryset, date_field,
def archive_week(request, year, week, queryset, date_field,
template_name=None, template_loader=loader,
- extra_context={}, allow_empty=True, context_processors=None,
+ extra_context=None, allow_empty=True, context_processors=None,
template_object_name='object', mimetype=None):
"""
Generic weekly archive view.
@@ -160,6 +163,7 @@ def archive_week(request, year, week, queryset, date_field,
object_list:
list of objects published in the given week
"""
+ if extra_context is None: extra_context = {}
try:
date = datetime.date(*time.strptime(year+'-0-'+week, '%Y-%w-%U')[:3])
except ValueError:
@@ -195,7 +199,7 @@ def archive_week(request, year, week, queryset, date_field,
def archive_day(request, year, month, day, queryset, date_field,
month_format='%b', day_format='%d', template_name=None,
- template_loader=loader, extra_context={}, allow_empty=False,
+ template_loader=loader, extra_context=None, allow_empty=False,
context_processors=None, template_object_name='object',
mimetype=None):
"""
@@ -212,6 +216,7 @@ def archive_day(request, year, month, day, queryset, date_field,
next_day
(datetime) the next day, or None if the current day is today
"""
+ if extra_context is None: extra_context = {}
try:
date = datetime.date(*time.strptime(year+month+day, '%Y'+month_format+day_format)[:3])
except ValueError:
@@ -261,7 +266,7 @@ def archive_today(request, **kwargs):
def object_detail(request, year, month, day, queryset, date_field,
month_format='%b', day_format='%d', object_id=None, slug=None,
slug_field=None, template_name=None, template_name_field=None,
- template_loader=loader, extra_context={}, context_processors=None,
+ template_loader=loader, extra_context=None, context_processors=None,
template_object_name='object', mimetype=None):
"""
Generic detail view from year/month/day/slug or year/month/day/id structure.
@@ -271,6 +276,7 @@ def object_detail(request, year, month, day, queryset, date_field,
object:
the object to be detailed
"""
+ if extra_context is None: extra_context = {}
try:
date = datetime.date(*time.strptime(year+month+day, '%Y'+month_format+day_format)[:3])
except ValueError:
View
6 django/views/generic/list_detail.py
@@ -6,7 +6,7 @@
def object_list(request, queryset, paginate_by=None, allow_empty=False,
template_name=None, template_loader=loader,
- extra_context={}, context_processors=None, template_object_name='object',
+ extra_context=None, context_processors=None, template_object_name='object',
mimetype=None):
"""
Generic list of objects.
@@ -34,6 +34,7 @@ def object_list(request, queryset, paginate_by=None, allow_empty=False,
hits
number of objects, total
"""
+ if extra_context is None: extra_context = {}
queryset = queryset._clone()
if paginate_by:
paginator = ObjectPaginator(queryset, paginate_by)
@@ -78,7 +79,7 @@ def object_list(request, queryset, paginate_by=None, allow_empty=False,
def object_detail(request, queryset, object_id=None, slug=None,
slug_field=None, template_name=None, template_name_field=None,
- template_loader=loader, extra_context={},
+ template_loader=loader, extra_context=None,
context_processors=None, template_object_name='object',
mimetype=None):
"""
@@ -89,6 +90,7 @@ def object_detail(request, queryset, object_id=None, slug=None,
object
the object
"""
+ if extra_context is None: extra_context = {}
model = queryset.model
if object_id:
queryset = queryset.filter(pk=object_id)
Please sign in to comment.
Something went wrong with that request. Please try again.