Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Browse files

Fixed #4040 -- Changed uses of has_key() to "in". Slight performance

improvement and forward-compatible with future Python releases. Patch from Gary
Wilson.


git-svn-id: http://code.djangoproject.com/svn/django/trunk@5091 bcc190cf-cafb-0310-a4f2-bffc1f526a37
  • Loading branch information...
commit 439cb4047fb583d08149f28e2ce66a8edfe0efa7 1 parent 6c02565
@malcolmt malcolmt authored
Showing with 112 additions and 92 deletions.
  1. +1 −1  django/bin/profiling/gather_profile_stats.py
  2. +1 −1  django/contrib/admin/templatetags/admin_modify.py
  3. +3 −3 django/contrib/admin/views/auth.py
  4. +5 −5 django/contrib/admin/views/decorators.py
  5. +19 −19 django/contrib/admin/views/main.py
  6. +1 −1  django/contrib/comments/templatetags/comments.py
  7. +6 −6 django/contrib/comments/views/comments.py
  8. +1 −1  django/contrib/sitemaps/views.py
  9. +1 −1  django/core/cache/backends/simple.py
  10. +2 −2 django/core/handlers/modpython.py
  11. +1 −1  django/core/handlers/wsgi.py
  12. +3 −3 django/core/management.py
  13. +6 −6 django/core/servers/basehttp.py
  14. +3 −3 django/core/validators.py
  15. +1 −1  django/db/backends/mysql_old/base.py
  16. +1 −1  django/db/backends/postgresql/base.py
  17. +1 −1  django/db/backends/util.py
  18. +1 −1  django/db/models/fields/__init__.py
  19. +1 −1  django/db/models/fields/generic.py
  20. +2 −2 django/db/models/fields/related.py
  21. +1 −1  django/db/models/loading.py
  22. +2 −2 django/db/models/options.py
  23. +6 −6 django/db/transaction.py
  24. +4 −4 django/http/__init__.py
  25. +1 −1  django/middleware/common.py
  26. +1 −1  django/newforms/forms.py
  27. +2 −2 django/newforms/widgets.py
  28. +1 −1  django/oldforms/__init__.py
  29. +1 −1  django/template/__init__.py
  30. +3 −3 django/template/context.py
  31. +4 −4 django/template/defaulttags.py
  32. +1 −1  django/utils/datastructures.py
  33. +1 −1  django/utils/functional.py
  34. +1 −1  django/utils/translation/trans_real.py
  35. +3 −3 django/views/i18n.py
  36. +2 −0  tests/regressiontests/dispatch/tests/test_saferef.py
  37. +18 −0 tests/regressiontests/httpwrappers/tests.py
View
2  django/bin/profiling/gather_profile_stats.py
@@ -22,7 +22,7 @@ def gather_stats(p):
else:
continue
print "Processing %s" % f
- if profiles.has_key(path):
+ if path in profiles:
profiles[path].add(prof)
else:
profiles[path] = prof
View
2  django/contrib/admin/templatetags/admin_modify.py
@@ -74,7 +74,7 @@ def __init__(self, bound_field_var):
self.bound_field_var = bound_field_var
def get_nodelist(cls, klass):
- if not cls.nodelists.has_key(klass):
+ if klass not in cls.nodelists:
try:
field_class_name = klass.__name__
template_name = "widget/%s.html" % class_name_to_underscored(field_class_name)
View
6 django/contrib/admin/views/auth.py
@@ -17,7 +17,7 @@ def user_add_stage(request):
if not errors:
new_user = manipulator.save(new_data)
msg = _('The %(name)s "%(obj)s" was added successfully.') % {'name': 'user', 'obj': new_user}
- if request.POST.has_key("_addanother"):
+ if "_addanother" in request.POST:
request.user.message_set.create(message=msg)
return HttpResponseRedirect(request.path)
else:
@@ -29,7 +29,7 @@ def user_add_stage(request):
return render_to_response('admin/auth/user/add_form.html', {
'title': _('Add user'),
'form': form,
- 'is_popup': request.REQUEST.has_key('_popup'),
+ 'is_popup': '_popup' in request.REQUEST,
'add': True,
'change': False,
'has_delete_permission': False,
@@ -63,7 +63,7 @@ def user_change_password(request, id):
return render_to_response('admin/auth/user/change_password.html', {
'title': _('Change password: %s') % escape(user.username),
'form': form,
- 'is_popup': request.REQUEST.has_key('_popup'),
+ 'is_popup': '_popup' in request.REQUEST,
'add': True,
'change': False,
'has_delete_permission': False,
View
10 django/contrib/admin/views/decorators.py
@@ -12,7 +12,7 @@
def _display_login_form(request, error_message=''):
request.session.set_test_cookie()
- if request.POST and request.POST.has_key('post_data'):
+ if request.POST and 'post_data' in request.POST:
# User has failed login BUT has previously saved post data.
post_data = request.POST['post_data']
elif request.POST:
@@ -48,7 +48,7 @@ def staff_member_required(view_func):
def _checklogin(request, *args, **kwargs):
if request.user.is_authenticated() and request.user.is_staff:
# The user is valid. Continue to the admin page.
- if request.POST.has_key('post_data'):
+ if 'post_data' in request.POST:
# User must have re-authenticated through a different window
# or tab.
request.POST = _decode_post_data(request.POST['post_data'])
@@ -57,7 +57,7 @@ def _checklogin(request, *args, **kwargs):
assert hasattr(request, 'session'), "The Django admin requires session middleware to be installed. Edit your MIDDLEWARE_CLASSES setting to insert 'django.contrib.sessions.middleware.SessionMiddleware'."
# If this isn't already the login page, display it.
- if not request.POST.has_key(LOGIN_FORM_KEY):
+ if LOGIN_FORM_KEY not in request.POST:
if request.POST:
message = _("Please log in again, because your session has expired. Don't worry: Your submission has been saved.")
else:
@@ -90,9 +90,9 @@ def _checklogin(request, *args, **kwargs):
if user.is_active and user.is_staff:
login(request, user)
# TODO: set last_login with an event.
- if request.POST.has_key('post_data'):
+ if 'post_data' in request.POST:
post_data = _decode_post_data(request.POST['post_data'])
- if post_data and not post_data.has_key(LOGIN_FORM_KEY):
+ if post_data and LOGIN_FORM_KEY not in post_data:
# overwrite request.POST with the saved post_data, and continue
request.POST = post_data
request.user = user
View
38 django/contrib/admin/views/main.py
@@ -257,17 +257,17 @@ def add_stage(request, app_label, model_name, show_delete=False, form_url='', po
msg = _('The %(name)s "%(obj)s" was added successfully.') % {'name': opts.verbose_name, 'obj': new_object}
# Here, we distinguish between different save types by checking for
# the presence of keys in request.POST.
- if request.POST.has_key("_continue"):
+ if "_continue" in request.POST:
request.user.message_set.create(message=msg + ' ' + _("You may edit it again below."))
- if request.POST.has_key("_popup"):
+ if "_popup" in request.POST:
post_url_continue += "?_popup=1"
return HttpResponseRedirect(post_url_continue % pk_value)
- if request.POST.has_key("_popup"):
+ if "_popup" in request.POST:
if type(pk_value) is str: # Quote if string, so JavaScript doesn't think it's a variable.
pk_value = '"%s"' % pk_value.replace('"', '\\"')
return HttpResponse('<script type="text/javascript">opener.dismissAddAnotherPopup(window, %s, "%s");</script>' % \
(pk_value, str(new_object).replace('"', '\\"')))
- elif request.POST.has_key("_addanother"):
+ elif "_addanother" in request.POST:
request.user.message_set.create(message=msg + ' ' + (_("You may add another %s below.") % opts.verbose_name))
return HttpResponseRedirect(request.path)
else:
@@ -288,7 +288,7 @@ def add_stage(request, app_label, model_name, show_delete=False, form_url='', po
c = template.RequestContext(request, {
'title': _('Add %s') % opts.verbose_name,
'form': form,
- 'is_popup': request.REQUEST.has_key('_popup'),
+ 'is_popup': '_popup' in request.REQUEST,
'show_delete': show_delete,
})
@@ -308,7 +308,7 @@ def change_stage(request, app_label, model_name, object_id):
if not request.user.has_perm(app_label + '.' + opts.get_change_permission()):
raise PermissionDenied
- if request.POST and request.POST.has_key("_saveasnew"):
+ if request.POST and "_saveasnew" in request.POST:
return add_stage(request, app_label, model_name, form_url='../../add/')
try:
@@ -343,16 +343,16 @@ def change_stage(request, app_label, model_name, object_id):
LogEntry.objects.log_action(request.user.id, ContentType.objects.get_for_model(model).id, pk_value, str(new_object), CHANGE, change_message)
msg = _('The %(name)s "%(obj)s" was changed successfully.') % {'name': opts.verbose_name, 'obj': new_object}
- if request.POST.has_key("_continue"):
+ if "_continue" in request.POST:
request.user.message_set.create(message=msg + ' ' + _("You may edit it again below."))
- if request.REQUEST.has_key('_popup'):
+ if '_popup' in request.REQUEST:
return HttpResponseRedirect(request.path + "?_popup=1")
else:
return HttpResponseRedirect(request.path)
- elif request.POST.has_key("_saveasnew"):
+ elif "_saveasnew" in request.POST:
request.user.message_set.create(message=_('The %(name)s "%(obj)s" was added successfully. You may edit it again below.') % {'name': opts.verbose_name, 'obj': new_object})
return HttpResponseRedirect("../%s/" % pk_value)
- elif request.POST.has_key("_addanother"):
+ elif "_addanother" in request.POST:
request.user.message_set.create(message=msg + ' ' + (_("You may add another %s below.") % opts.verbose_name))
return HttpResponseRedirect("../add/")
else:
@@ -392,7 +392,7 @@ def change_stage(request, app_label, model_name, object_id):
'form': form,
'object_id': object_id,
'original': manipulator.original_object,
- 'is_popup': request.REQUEST.has_key('_popup'),
+ 'is_popup': '_popup' in request.REQUEST,
})
return render_change_form(model, manipulator, c, change=True)
change_stage = staff_member_required(never_cache(change_stage))
@@ -558,12 +558,12 @@ def __init__(self, request, model):
self.page_num = int(request.GET.get(PAGE_VAR, 0))
except ValueError:
self.page_num = 0
- self.show_all = request.GET.has_key(ALL_VAR)
- self.is_popup = request.GET.has_key(IS_POPUP_VAR)
+ self.show_all = ALL_VAR in request.GET
+ self.is_popup = IS_POPUP_VAR in request.GET
self.params = dict(request.GET.items())
- if self.params.has_key(PAGE_VAR):
+ if PAGE_VAR in self.params:
del self.params[PAGE_VAR]
- if self.params.has_key(ERROR_FLAG):
+ if ERROR_FLAG in self.params:
del self.params[ERROR_FLAG]
self.order_field, self.order_type = self.get_ordering()
@@ -594,7 +594,7 @@ def get_query_string(self, new_params=None, remove=None):
if k.startswith(r):
del p[k]
for k, v in new_params.items():
- if p.has_key(k) and v is None:
+ if k in p and v is None:
del p[k]
elif v is not None:
p[k] = v
@@ -656,7 +656,7 @@ def get_ordering(self):
order_field, order_type = ordering[0][1:], 'desc'
else:
order_field, order_type = ordering[0], 'asc'
- if params.has_key(ORDER_VAR):
+ if ORDER_VAR in params:
try:
field_name = lookup_opts.admin.list_display[int(params[ORDER_VAR])]
try:
@@ -674,7 +674,7 @@ def get_ordering(self):
order_field = f.name
except (IndexError, ValueError):
pass # Invalid ordering specified. Just use the default.
- if params.has_key(ORDER_TYPE_VAR) and params[ORDER_TYPE_VAR] in ('asc', 'desc'):
+ if ORDER_TYPE_VAR in params and params[ORDER_TYPE_VAR] in ('asc', 'desc'):
order_type = params[ORDER_TYPE_VAR]
return order_field, order_type
@@ -682,7 +682,7 @@ def get_query_set(self):
qs = self.manager.get_query_set()
lookup_params = self.params.copy() # a dictionary of the query string
for i in (ALL_VAR, ORDER_VAR, ORDER_TYPE_VAR, SEARCH_VAR, IS_POPUP_VAR):
- if lookup_params.has_key(i):
+ if i in lookup_params:
del lookup_params[i]
# Apply lookup parameters from the query string.
View
2  django/contrib/comments/templatetags/comments.py
@@ -116,7 +116,7 @@ def render(self, context):
comment_list = get_list_function(**kwargs).order_by(self.ordering + 'submit_date').select_related()
if not self.free:
- if context.has_key('user') and context['user'].is_authenticated():
+ if 'user' in context and context['user'].is_authenticated():
user_id = context['user'].id
context['user_can_moderate_comments'] = Comment.objects.user_is_moderator(context['user'])
else:
View
12 django/contrib/comments/views/comments.py
@@ -217,10 +217,10 @@ def post_comment(request):
errors = manipulator.get_validation_errors(new_data)
# If user gave correct username/password and wasn't already logged in, log them in
# so they don't have to enter a username/password again.
- if manipulator.get_user() and not manipulator.get_user().is_authenticated() and new_data.has_key('password') and manipulator.get_user().check_password(new_data['password']):
+ if manipulator.get_user() and not manipulator.get_user().is_authenticated() and 'password' in new_data and manipulator.get_user().check_password(new_data['password']):
from django.contrib.auth import login
login(request, manipulator.get_user())
- if errors or request.POST.has_key('preview'):
+ if errors or 'preview' in request.POST:
class CommentFormWrapper(oldforms.FormWrapper):
def __init__(self, manipulator, new_data, errors, rating_choices):
oldforms.FormWrapper.__init__(self, manipulator, new_data, errors)
@@ -244,7 +244,7 @@ def ratings(self):
'rating_range': rating_range,
'rating_choices': rating_choices,
}, context_instance=RequestContext(request))
- elif request.POST.has_key('post'):
+ elif 'post' in request.POST:
# If the IP is banned, mail the admins, do NOT save the comment, and
# serve up the "Thanks for posting" page as if the comment WAS posted.
if request.META['REMOTE_ADDR'] in settings.BANNED_IPS:
@@ -298,7 +298,7 @@ def post_free_comment(request):
new_data['is_public'] = IS_PUBLIC in option_list
manipulator = PublicFreeCommentManipulator()
errors = manipulator.get_validation_errors(new_data)
- if errors or request.POST.has_key('preview'):
+ if errors or 'preview' in request.POST:
comment = errors and '' or manipulator.get_comment(new_data)
return render_to_response('comments/free_preview.html', {
'comment': comment,
@@ -307,7 +307,7 @@ def post_free_comment(request):
'target': target,
'hash': security_hash,
}, context_instance=RequestContext(request))
- elif request.POST.has_key('post'):
+ elif 'post' in request.POST:
# If the IP is banned, mail the admins, do NOT save the comment, and
# serve up the "Thanks for posting" page as if the comment WAS posted.
if request.META['REMOTE_ADDR'] in settings.BANNED_IPS:
@@ -330,7 +330,7 @@ def comment_was_posted(request):
The object the comment was posted on
"""
obj = None
- if request.GET.has_key('c'):
+ if 'c' in request.GET:
content_type_id, object_id = request.GET['c'].split(':')
try:
content_type = ContentType.objects.get(pk=content_type_id)
View
2  django/contrib/sitemaps/views.py
@@ -16,7 +16,7 @@ def index(request, sitemaps):
def sitemap(request, sitemaps, section=None):
maps, urls = [], []
if section is not None:
- if not sitemaps.has_key(section):
+ if section not in sitemaps:
raise Http404("No sitemap available for section: %r" % section)
maps.append(sitemaps[section])
else:
View
2  django/core/cache/backends/simple.py
@@ -52,7 +52,7 @@ def delete(self, key):
pass
def has_key(self, key):
- return self._cache.has_key(key)
+ return key in self._cache
def _cull(self):
if self._cull_frequency == 0:
View
4 django/core/handlers/modpython.py
@@ -42,11 +42,11 @@ def get_full_path(self):
def is_secure(self):
# Note: modpython 3.2.10+ has req.is_https(), but we need to support previous versions
- return self._req.subprocess_env.has_key('HTTPS') and self._req.subprocess_env['HTTPS'] == 'on'
+ return 'HTTPS' in self._req.subprocess_env and self._req.subprocess_env['HTTPS'] == 'on'
def _load_post_and_files(self):
"Populates self._post and self._files"
- if self._req.headers_in.has_key('content-type') and self._req.headers_in['content-type'].startswith('multipart'):
+ if 'content-type' in self._req.headers_in and self._req.headers_in['content-type'].startswith('multipart'):
self._post, self._files = http.parse_file_upload(self._req.headers_in, self.raw_post_data)
else:
self._post, self._files = http.QueryDict(self.raw_post_data), datastructures.MultiValueDict()
View
2  django/core/handlers/wsgi.py
@@ -103,7 +103,7 @@ def get_full_path(self):
return '%s%s' % (self.path, self.environ.get('QUERY_STRING', '') and ('?' + self.environ.get('QUERY_STRING', '')) or '')
def is_secure(self):
- return self.environ.has_key('HTTPS') and self.environ['HTTPS'] == 'on'
+ return 'HTTPS' in self.environ and self.environ['HTTPS'] == 'on'
def _load_post_and_files(self):
# Populates self._post and self._files
View
6 django/core/management.py
@@ -314,7 +314,7 @@ def get_sql_delete(app):
# Drop the table now
output.append('%s %s;' % (style.SQL_KEYWORD('DROP TABLE'),
style.SQL_TABLE(backend.quote_name(model._meta.db_table))))
- if backend.supports_constraints and references_to_delete.has_key(model):
+ if backend.supports_constraints and model in references_to_delete:
for rel_class, f in references_to_delete[model]:
table = rel_class._meta.db_table
col = f.column
@@ -843,7 +843,7 @@ def inspectdb():
att_name += '_field'
comment_notes.append('Field renamed because it was a Python reserved word.')
- if relations.has_key(i):
+ if i in relations:
rel_to = relations[i][1] == table_name and "'self'" or table2model(relations[i][1])
field_type = 'ForeignKey(%s' % rel_to
if att_name.endswith('_id'):
@@ -1550,7 +1550,7 @@ def execute_from_command_line(action_mapping=DEFAULT_ACTION_MAPPING, argv=None):
action = args[0]
except IndexError:
parser.print_usage_and_exit()
- if not action_mapping.has_key(action):
+ if action not in action_mapping:
print_error("Your action, %r, was invalid." % action, argv[0])
# Switch to English, because django-admin.py creates database content
View
12 django/core/servers/basehttp.py
@@ -208,15 +208,15 @@ def guess_scheme(environ):
else:
return 'http'
-_hoppish = {
+_hop_headers = {
'connection':1, 'keep-alive':1, 'proxy-authenticate':1,
'proxy-authorization':1, 'te':1, 'trailers':1, 'transfer-encoding':1,
'upgrade':1
-}.has_key
+}
def is_hop_by_hop(header_name):
"""Return true if 'header_name' is an HTTP/1.1 "Hop-by-Hop" header"""
- return _hoppish(header_name.lower())
+ return header_name.lower() in _hop_headers
class ServerHandler(object):
"""Manage the invocation of a WSGI application"""
@@ -334,7 +334,7 @@ def cleanup_headers(self):
Subclasses can extend this to add other defaults.
"""
- if not self.headers.has_key('Content-Length'):
+ if 'Content-Length' not in self.headers:
self.set_content_length()
def start_response(self, status, headers,exc_info=None):
@@ -368,11 +368,11 @@ def send_preamble(self):
if self.origin_server:
if self.client_is_modern():
self._write('HTTP/%s %s\r\n' % (self.http_version,self.status))
- if not self.headers.has_key('Date'):
+ if 'Date' not in self.headers:
self._write(
'Date: %s\r\n' % time.asctime(time.gmtime(time.time()))
)
- if self.server_software and not self.headers.has_key('Server'):
+ if self.server_software and 'Server' not in self.headers:
self._write('Server: %s\r\n' % self.server_software)
else:
self._write('Status: %s\r\n' % self.status)
View
6 django/core/validators.py
@@ -284,7 +284,7 @@ def __init__(self, other_field, other_value, validator_list):
self.always_test = True
def __call__(self, field_data, all_data):
- if all_data.has_key(self.other_field) and all_data[self.other_field] == self.other_value:
+ if self.other_field in all_data and all_data[self.other_field] == self.other_value:
for v in self.validator_list:
v(field_data, all_data)
@@ -322,7 +322,7 @@ def __init__(self, other_field, other_value, error_message=None, other_label=Non
self.always_test = True
def __call__(self, field_data, all_data):
- if all_data.has_key(self.other_field) and all_data[self.other_field] == self.other_value and not field_data:
+ if self.other_field in all_data and all_data[self.other_field] == self.other_value and not field_data:
raise ValidationError(self.error_message)
class RequiredIfOtherFieldDoesNotEqual(object):
@@ -335,7 +335,7 @@ def __init__(self, other_field, other_value, other_label=None, error_message=Non
self.always_test = True
def __call__(self, field_data, all_data):
- if all_data.has_key(self.other_field) and all_data[self.other_field] != self.other_value and not field_data:
+ if self.other_field in all_data and all_data[self.other_field] != self.other_value and not field_data:
raise ValidationError(self.error_message)
class IsLessThanOtherField(object):
View
2  django/db/backends/mysql_old/base.py
@@ -53,7 +53,7 @@ def executemany(self, sql, param_list):
raise Database.Warning, "%s: %s" % (w, self.cursor.fetchall())
def __getattr__(self, attr):
- if self.__dict__.has_key(attr):
+ if attr in self.__dict__:
return self.__dict__[attr]
else:
return getattr(self.cursor, attr)
View
2  django/db/backends/postgresql/base.py
@@ -48,7 +48,7 @@ def executemany(self, sql, param_list):
return self.cursor.executemany(sql, new_param_list)
def __getattr__(self, attr):
- if self.__dict__.has_key(attr):
+ if attr in self.__dict__:
return self.__dict__[attr]
else:
return getattr(self.cursor, attr)
View
2  django/db/backends/util.py
@@ -33,7 +33,7 @@ def executemany(self, sql, param_list):
})
def __getattr__(self, attr):
- if self.__dict__.has_key(attr):
+ if attr in self.__dict__:
return self.__dict__[attr]
else:
return getattr(self.cursor, attr)
View
2  django/db/models/fields/__init__.py
@@ -779,7 +779,7 @@ def __init__(self, *args, **kwargs):
kwargs['maxlength'] = kwargs.get('maxlength', 50)
kwargs.setdefault('validator_list', []).append(validators.isSlug)
# Set db_index=True unless it's been set manually.
- if not kwargs.has_key('db_index'):
+ if 'db_index' not in kwargs:
kwargs['db_index'] = True
Field.__init__(self, *args, **kwargs)
View
2  django/db/models/fields/generic.py
@@ -37,7 +37,7 @@ def contribute_to_class(self, cls, name):
def instance_pre_init(self, signal, sender, args, kwargs):
# Handle initalizing an object with the generic FK instaed of
# content-type/object-id fields.
- if kwargs.has_key(self.name):
+ if self.name in kwargs:
value = kwargs.pop(self.name)
kwargs[self.ct_field] = self.get_content_type(value)
kwargs[self.fk_field] = value._get_pk_val()
View
4 django/db/models/fields/related.py
@@ -474,7 +474,7 @@ def __init__(self, to, to_field=None, **kwargs):
to_field = to_field or to._meta.pk.name
kwargs['verbose_name'] = kwargs.get('verbose_name', '')
- if kwargs.has_key('edit_inline_type'):
+ if 'edit_inline_type' in kwargs:
import warnings
warnings.warn("edit_inline_type is deprecated. Use edit_inline instead.")
kwargs['edit_inline'] = kwargs.pop('edit_inline_type')
@@ -567,7 +567,7 @@ def __init__(self, to, to_field=None, **kwargs):
to_field = to_field or to._meta.pk.name
kwargs['verbose_name'] = kwargs.get('verbose_name', '')
- if kwargs.has_key('edit_inline_type'):
+ if 'edit_inline_type' in kwargs:
import warnings
warnings.warn("edit_inline_type is deprecated. Use edit_inline instead.")
kwargs['edit_inline'] = kwargs.pop('edit_inline_type')
View
2  django/db/models/loading.py
@@ -103,7 +103,7 @@ def register_models(app_label, *models):
# in the _app_models dictionary
model_name = model._meta.object_name.lower()
model_dict = _app_models.setdefault(app_label, {})
- if model_dict.has_key(model_name):
+ if model_name in model_dict:
# The same model may be imported via different paths (e.g.
# appname.models and project.appname.models). We use the source
# filename as a means to detect identity.
View
4 django/db/models/options.py
@@ -140,7 +140,7 @@ def get_data_holders(self, follow=None):
def get_follow(self, override=None):
follow = {}
for f in self.fields + self.many_to_many + self.get_all_related_objects():
- if override and override.has_key(f.name):
+ if override and f.name in override:
child_override = override[f.name]
else:
child_override = None
@@ -182,7 +182,7 @@ def has_field_type(self, field_type, follow=None):
# TODO: follow
if not hasattr(self, '_field_types'):
self._field_types = {}
- if not self._field_types.has_key(field_type):
+ if field_type not in self._field_types:
try:
# First check self.fields.
for f in self.fields:
View
12 django/db/transaction.py
@@ -46,12 +46,12 @@ def enter_transaction_management():
when no current block is running).
"""
thread_ident = thread.get_ident()
- if state.has_key(thread_ident) and state[thread_ident]:
+ if thread_ident in state and state[thread_ident]:
state[thread_ident].append(state[thread_ident][-1])
else:
state[thread_ident] = []
state[thread_ident].append(settings.TRANSACTIONS_MANAGED)
- if not dirty.has_key(thread_ident):
+ if thread_ident not in dirty:
dirty[thread_ident] = False
def leave_transaction_management():
@@ -61,7 +61,7 @@ def leave_transaction_management():
those from outside. (Commits are on connection level.)
"""
thread_ident = thread.get_ident()
- if state.has_key(thread_ident) and state[thread_ident]:
+ if thread_ident in state and state[thread_ident]:
del state[thread_ident][-1]
else:
raise TransactionManagementError("This code isn't under transaction management")
@@ -84,7 +84,7 @@ def set_dirty():
changes waiting for commit.
"""
thread_ident = thread.get_ident()
- if dirty.has_key(thread_ident):
+ if thread_ident in dirty:
dirty[thread_ident] = True
else:
raise TransactionManagementError("This code isn't under transaction management")
@@ -96,7 +96,7 @@ def set_clean():
should happen.
"""
thread_ident = thread.get_ident()
- if dirty.has_key(thread_ident):
+ if thread_ident in dirty:
dirty[thread_ident] = False
else:
raise TransactionManagementError("This code isn't under transaction management")
@@ -106,7 +106,7 @@ def is_managed():
Checks whether the transaction manager is in manual or in auto state.
"""
thread_ident = thread.get_ident()
- if state.has_key(thread_ident):
+ if thread_ident in state:
if state[thread_ident]:
return state[thread_ident][-1]
return settings.TRANSACTIONS_MANAGED
View
8 django/http/__init__.py
@@ -29,12 +29,12 @@ def __repr__(self):
def __getitem__(self, key):
for d in (self.POST, self.GET):
- if d.has_key(key):
+ if key in d:
return d[key]
raise KeyError, "%s not found in either POST or GET" % key
def has_key(self, key):
- return self.GET.has_key(key) or self.POST.has_key(key)
+ return key in self.GET or key in self.POST
def get_full_path(self):
return ''
@@ -57,7 +57,7 @@ def parse_file_upload(header_dict, post_data):
# name_dict is something like {'name': 'file', 'filename': 'test.txt'} for file uploads
# or {'name': 'blah'} for POST fields
# We assume all uploaded files have a 'filename' set.
- if name_dict.has_key('filename'):
+ if 'filename' in name_dict:
assert type([]) != type(submessage.get_payload()), "Nested MIME messages are not supported"
if not name_dict['filename'].strip():
continue
@@ -66,7 +66,7 @@ def parse_file_upload(header_dict, post_data):
filename = name_dict['filename'][name_dict['filename'].rfind("\\")+1:]
FILES.appendlist(name_dict['name'], {
'filename': filename,
- 'content-type': (submessage.has_key('Content-Type') and submessage['Content-Type'] or None),
+ 'content-type': 'Content-Type' in submessage and submessage['Content-Type'] or None,
'content': submessage.get_payload(),
})
else:
View
2  django/middleware/common.py
@@ -25,7 +25,7 @@ def process_request(self, request):
"""
# Check for denied User-Agents
- if request.META.has_key('HTTP_USER_AGENT'):
+ if 'HTTP_USER_AGENT' in request.META:
for user_agent_regex in settings.DISALLOWED_USER_AGENTS:
if user_agent_regex.search(request.META['HTTP_USER_AGENT']):
return http.HttpResponseForbidden('<h1>Forbidden</h1>')
View
2  django/newforms/forms.py
@@ -244,7 +244,7 @@ def _errors(self):
def as_widget(self, widget, attrs=None):
attrs = attrs or {}
auto_id = self.auto_id
- if auto_id and not attrs.has_key('id') and not widget.attrs.has_key('id'):
+ if auto_id and 'id' not in attrs and 'id' not in widget.attrs:
attrs['id'] = auto_id
if not self.form.is_bound:
data = self.form.initial.get(self.name, self.field.initial)
View
4 django/newforms/widgets.py
@@ -230,7 +230,7 @@ def is_checked(self):
return self.value == self.choice_value
def tag(self):
- if self.attrs.has_key('id'):
+ if 'id' in self.attrs:
self.attrs['id'] = '%s_%s' % (self.attrs['id'], self.index)
final_attrs = dict(self.attrs, type='radio', name=self.name, value=self.choice_value)
if self.is_checked():
@@ -276,7 +276,7 @@ def id_for_label(self, id_):
class CheckboxSelectMultiple(SelectMultiple):
def render(self, name, value, attrs=None, choices=()):
if value is None: value = []
- has_id = attrs and attrs.has_key('id')
+ has_id = attrs and 'id' in attrs
final_attrs = self.build_attrs(attrs, name=name)
output = [u'<ul>']
str_values = set([smart_unicode(v) for v in value]) # Normalize to strings.
View
2  django/oldforms/__init__.py
@@ -329,7 +329,7 @@ def extract_data(self, data_dict):
def convert_post_data(self, new_data):
name = self.get_member_name()
- if new_data.has_key(self.field_name):
+ if self.field_name in new_data:
d = new_data.getlist(self.field_name)
try:
converted_data = [self.__class__.html2python(data) for data in d]
View
2  django/template/__init__.py
@@ -338,7 +338,7 @@ def compile_filter(self, token):
return FilterExpression(token, self)
def find_filter(self, filter_name):
- if self.filters.has_key(filter_name):
+ if filter_name in self.filters:
return self.filters[filter_name]
else:
raise TemplateSyntaxError, "Invalid filter: '%s'" % filter_name
View
6 django/template/context.py
@@ -35,7 +35,7 @@ def __setitem__(self, key, value):
def __getitem__(self, key):
"Get a variable's value, starting at the current context and going upward"
for d in self.dicts:
- if d.has_key(key):
+ if key in d:
return d[key]
raise KeyError(key)
@@ -45,7 +45,7 @@ def __delitem__(self, key):
def has_key(self, key):
for d in self.dicts:
- if d.has_key(key):
+ if key in d:
return True
return False
@@ -54,7 +54,7 @@ def __contains__(self, key):
def get(self, key, otherwise=None):
for d in self.dicts:
- if d.has_key(key):
+ if key in d:
return d[key]
return otherwise
View
8 django/template/defaulttags.py
@@ -87,7 +87,7 @@ def get_nodes_by_type(self, nodetype):
def render(self, context):
nodelist = NodeList()
- if context.has_key('forloop'):
+ if 'forloop' in context:
parentloop = context['forloop']
else:
parentloop = {}
@@ -133,7 +133,7 @@ def __init__(self, nodelist, *varlist):
self._varlist = varlist
def render(self, context):
- if context.has_key('forloop') and context['forloop']['first']:
+ if 'forloop' in context and context['forloop']['first']:
self._last_seen = None
try:
if self._varlist:
@@ -432,7 +432,7 @@ def cycle(parser, token):
name = args[1]
if not hasattr(parser, '_namedCycleNodes'):
raise TemplateSyntaxError("No named cycles in template: '%s' is not defined" % name)
- if not parser._namedCycleNodes.has_key(name):
+ if name not in parser._namedCycleNodes:
raise TemplateSyntaxError("Named cycle '%s' does not exist" % name)
return parser._namedCycleNodes[name]
@@ -911,7 +911,7 @@ def templatetag(parser, token):
if len(bits) != 2:
raise TemplateSyntaxError, "'templatetag' statement takes one argument"
tag = bits[1]
- if not TemplateTagNode.mapping.has_key(tag):
+ if tag not in TemplateTagNode.mapping:
raise TemplateSyntaxError, "Invalid templatetag argument: '%s'. Must be one of: %s" % \
(tag, TemplateTagNode.mapping.keys())
return TemplateTagNode(tag)
View
2  django/utils/datastructures.py
@@ -42,7 +42,7 @@ def items(self):
def has_key(self, key):
for dict in self.dicts:
- if dict.has_key(key):
+ if key in dict:
return True
return False
View
2  django/utils/functional.py
@@ -42,7 +42,7 @@ def __wrapper__(*args, **kw):
res = self.__func(*self.__args, **self.__kw)
return self.__dispatch[type(res)][funcname](res, *args, **kw)
- if not self.__dispatch.has_key(klass):
+ if klass not in self.__dispatch:
self.__dispatch[klass] = {}
self.__dispatch[klass][funcname] = func
return __wrapper__
View
2  django/utils/translation/trans_real.py
@@ -199,7 +199,7 @@ def deactivate():
will resolve against the default translation object, again.
"""
global _active
- if _active.has_key(currentThread()):
+ if currentThread() in _active:
del _active[currentThread()]
def get_language():
View
6 django/views/i18n.py
@@ -97,7 +97,7 @@ def javascript_catalog(request, domain='djangojs', packages=None):
deliver your JavaScript source from Django templates.
"""
if request.GET:
- if request.GET.has_key('language'):
+ if 'language' in request.GET:
if check_for_language(request.GET['language']):
activate(request.GET['language'])
if packages is None:
@@ -136,7 +136,7 @@ def javascript_catalog(request, domain='djangojs', packages=None):
t.update(catalog._catalog)
src = [LibHead]
plural = None
- if t.has_key(''):
+ if '' in t:
for l in t[''].split('\n'):
if l.startswith('Plural-Forms:'):
plural = l.split(':',1)[1].strip()
@@ -155,7 +155,7 @@ def javascript_catalog(request, domain='djangojs', packages=None):
if type(k) in (str, unicode):
csrc.append("catalog['%s'] = '%s';\n" % (javascript_quote(k), javascript_quote(v)))
elif type(k) == tuple:
- if not pdict.has_key(k[0]):
+ if k[0] not in pdict:
pdict[k[0]] = k[1]
else:
pdict[k[0]] = max(k[1], pdict[k[0]])
View
2  tests/regressiontests/dispatch/tests/test_saferef.py
@@ -55,8 +55,10 @@ def testShortCircuit (self):
for t in self.ts:
if hasattr(t, 'x'):
self.assert_(sd.has_key(safeRef(t.x)))
+ self.assert_(safeRef(t.x) in sd)
else:
self.assert_(sd.has_key(safeRef(t)))
+ self.assert_(safeRef(t) in sd)
def testRepresentation (self):
"""Test that the reference object's representation works
View
18 tests/regressiontests/httpwrappers/tests.py
@@ -34,6 +34,9 @@
>>> q.has_key('foo')
False
+>>> 'foo' in q
+False
+
>>> q.items()
[]
@@ -124,6 +127,9 @@
>>> q.has_key('foo')
True
+>>> 'foo' in q
+True
+
>>> q.items()
[('foo', 'another'), ('name', 'john')]
@@ -218,9 +224,15 @@
>>> q.has_key('foo')
True
+>>> 'foo' in q
+True
+
>>> q.has_key('bar')
False
+>>> 'bar' in q
+False
+
>>> q.items()
[('foo', 'bar')]
@@ -303,9 +315,15 @@
>>> q.has_key('vote')
True
+>>> 'vote' in q
+True
+
>>> q.has_key('foo')
False
+>>> 'foo' in q
+False
+
>>> q.items()
[('vote', 'no')]
Please sign in to comment.
Something went wrong with that request. Please try again.