From 439cb4047fb583d08149f28e2ce66a8edfe0efa7 Mon Sep 17 00:00:00 2001 From: Malcolm Tredinnick <malcolm.tredinnick@gmail.com> Date: Thu, 26 Apr 2007 13:30:48 +0000 Subject: [PATCH] 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 --- django/bin/profiling/gather_profile_stats.py | 2 +- .../admin/templatetags/admin_modify.py | 2 +- django/contrib/admin/views/auth.py | 6 +-- django/contrib/admin/views/decorators.py | 10 ++--- django/contrib/admin/views/main.py | 38 +++++++++---------- .../contrib/comments/templatetags/comments.py | 2 +- django/contrib/comments/views/comments.py | 12 +++--- django/contrib/sitemaps/views.py | 2 +- django/core/cache/backends/simple.py | 2 +- django/core/handlers/modpython.py | 4 +- django/core/handlers/wsgi.py | 2 +- django/core/management.py | 6 +-- django/core/servers/basehttp.py | 12 +++--- django/core/validators.py | 6 +-- django/db/backends/mysql_old/base.py | 2 +- django/db/backends/postgresql/base.py | 2 +- django/db/backends/util.py | 2 +- django/db/models/fields/__init__.py | 2 +- django/db/models/fields/generic.py | 2 +- django/db/models/fields/related.py | 4 +- django/db/models/loading.py | 2 +- django/db/models/options.py | 4 +- django/db/transaction.py | 12 +++--- django/http/__init__.py | 8 ++-- django/middleware/common.py | 2 +- django/newforms/forms.py | 2 +- django/newforms/widgets.py | 4 +- django/oldforms/__init__.py | 2 +- django/template/__init__.py | 2 +- django/template/context.py | 6 +-- django/template/defaulttags.py | 8 ++-- django/utils/datastructures.py | 2 +- django/utils/functional.py | 2 +- django/utils/translation/trans_real.py | 2 +- django/views/i18n.py | 6 +-- .../dispatch/tests/test_saferef.py | 2 + tests/regressiontests/httpwrappers/tests.py | 18 +++++++++ 37 files changed, 112 insertions(+), 92 deletions(-) diff --git a/django/bin/profiling/gather_profile_stats.py b/django/bin/profiling/gather_profile_stats.py index 852f16229d..c0844930e9 100644 --- a/django/bin/profiling/gather_profile_stats.py +++ b/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 diff --git a/django/contrib/admin/templatetags/admin_modify.py b/django/contrib/admin/templatetags/admin_modify.py index e708b876bd..f9cad005d5 100644 --- a/django/contrib/admin/templatetags/admin_modify.py +++ b/django/contrib/admin/templatetags/admin_modify.py @@ -74,7 +74,7 @@ class FieldWidgetNode(template.Node): 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) diff --git a/django/contrib/admin/views/auth.py b/django/contrib/admin/views/auth.py index bea1f8533c..c6ad0c3a95 100644 --- a/django/contrib/admin/views/auth.py +++ b/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, diff --git a/django/contrib/admin/views/decorators.py b/django/contrib/admin/views/decorators.py index bdd8257b2e..5389ca4dff 100644 --- a/django/contrib/admin/views/decorators.py +++ b/django/contrib/admin/views/decorators.py @@ -12,7 +12,7 @@ LOGIN_FORM_KEY = 'this_is_the_login_form' 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 staff_member_required(view_func): 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 staff_member_required(view_func): 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 diff --git a/django/contrib/admin/views/main.py b/django/contrib/admin/views/main.py index 0e962adf18..5edc1fc19d 100644 --- a/django/contrib/admin/views/main.py +++ b/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 @@ class ChangeList(object): 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 @@ class ChangeList(object): 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 @@ class ChangeList(object): 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 @@ class ChangeList(object): 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 @@ class ChangeList(object): 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. diff --git a/django/contrib/comments/templatetags/comments.py b/django/contrib/comments/templatetags/comments.py index 80d4bf24ab..5c02c16f95 100644 --- a/django/contrib/comments/templatetags/comments.py +++ b/django/contrib/comments/templatetags/comments.py @@ -116,7 +116,7 @@ class CommentListNode(template.Node): 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: diff --git a/django/contrib/comments/views/comments.py b/django/contrib/comments/views/comments.py index 12330afe41..73a9b2c480 100644 --- a/django/contrib/comments/views/comments.py +++ b/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 post_comment(request): '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) diff --git a/django/contrib/sitemaps/views.py b/django/contrib/sitemaps/views.py index 576e3d0bb8..d615c8e661 100644 --- a/django/contrib/sitemaps/views.py +++ b/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: diff --git a/django/core/cache/backends/simple.py b/django/core/cache/backends/simple.py index 175944a75a..3fcad8c7ad 100644 --- a/django/core/cache/backends/simple.py +++ b/django/core/cache/backends/simple.py @@ -52,7 +52,7 @@ class CacheClass(BaseCache): 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: diff --git a/django/core/handlers/modpython.py b/django/core/handlers/modpython.py index 5fc41a048b..6370cab47c 100644 --- a/django/core/handlers/modpython.py +++ b/django/core/handlers/modpython.py @@ -42,11 +42,11 @@ class ModPythonRequest(http.HttpRequest): 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() diff --git a/django/core/handlers/wsgi.py b/django/core/handlers/wsgi.py index 71cfecd9a0..4320b69627 100644 --- a/django/core/handlers/wsgi.py +++ b/django/core/handlers/wsgi.py @@ -103,7 +103,7 @@ class WSGIRequest(http.HttpRequest): 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 diff --git a/django/core/management.py b/django/core/management.py index 1e4f33c2dd..0f8de891a1 100644 --- a/django/core/management.py +++ b/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 diff --git a/django/core/servers/basehttp.py b/django/core/servers/basehttp.py index a16b8b675a..80a0bf6a91 100644 --- a/django/core/servers/basehttp.py +++ b/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 @@ class ServerHandler(object): 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 @@ class ServerHandler(object): 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) diff --git a/django/core/validators.py b/django/core/validators.py index bd7d790e04..26165c4af1 100644 --- a/django/core/validators.py +++ b/django/core/validators.py @@ -284,7 +284,7 @@ class ValidateIfOtherFieldEquals(object): 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 @@ class RequiredIfOtherFieldEquals(object): 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 @@ class RequiredIfOtherFieldDoesNotEqual(object): 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): diff --git a/django/db/backends/mysql_old/base.py b/django/db/backends/mysql_old/base.py index 01eff22641..d56b8513f9 100644 --- a/django/db/backends/mysql_old/base.py +++ b/django/db/backends/mysql_old/base.py @@ -53,7 +53,7 @@ class MysqlDebugWrapper: 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) diff --git a/django/db/backends/postgresql/base.py b/django/db/backends/postgresql/base.py index bb52711191..dc0fbe3ab9 100644 --- a/django/db/backends/postgresql/base.py +++ b/django/db/backends/postgresql/base.py @@ -48,7 +48,7 @@ class UnicodeCursorWrapper(object): 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) diff --git a/django/db/backends/util.py b/django/db/backends/util.py index d8f86fef4f..d14a337ca2 100644 --- a/django/db/backends/util.py +++ b/django/db/backends/util.py @@ -33,7 +33,7 @@ class CursorDebugWrapper(object): }) 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) diff --git a/django/db/models/fields/__init__.py b/django/db/models/fields/__init__.py index 466897ad86..91629cd679 100644 --- a/django/db/models/fields/__init__.py +++ b/django/db/models/fields/__init__.py @@ -779,7 +779,7 @@ class SlugField(Field): 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) diff --git a/django/db/models/fields/generic.py b/django/db/models/fields/generic.py index 480ee689c9..f995ab2044 100644 --- a/django/db/models/fields/generic.py +++ b/django/db/models/fields/generic.py @@ -37,7 +37,7 @@ class GenericForeignKey(object): 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() diff --git a/django/db/models/fields/related.py b/django/db/models/fields/related.py index fad9c164c1..e8152f32e7 100644 --- a/django/db/models/fields/related.py +++ b/django/db/models/fields/related.py @@ -474,7 +474,7 @@ class ForeignKey(RelatedField, Field): 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 @@ class OneToOneField(RelatedField, IntegerField): 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') diff --git a/django/db/models/loading.py b/django/db/models/loading.py index f4aff2438b..224f5e8451 100644 --- a/django/db/models/loading.py +++ b/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. diff --git a/django/db/models/options.py b/django/db/models/options.py index 51cf0a019b..dd6c586ddd 100644 --- a/django/db/models/options.py +++ b/django/db/models/options.py @@ -140,7 +140,7 @@ class Options(object): 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 @@ class Options(object): # 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: diff --git a/django/db/transaction.py b/django/db/transaction.py index 4a0658e1c3..bb90713525 100644 --- a/django/db/transaction.py +++ b/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 diff --git a/django/http/__init__.py b/django/http/__init__.py index ed2c128a16..a0c51ff0da 100644 --- a/django/http/__init__.py +++ b/django/http/__init__.py @@ -29,12 +29,12 @@ class HttpRequest(object): 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: diff --git a/django/middleware/common.py b/django/middleware/common.py index 9891b1efad..2c72c9a583 100644 --- a/django/middleware/common.py +++ b/django/middleware/common.py @@ -25,7 +25,7 @@ class CommonMiddleware(object): """ # 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>') diff --git a/django/newforms/forms.py b/django/newforms/forms.py index 1f37da91ff..3df7a9e834 100644 --- a/django/newforms/forms.py +++ b/django/newforms/forms.py @@ -244,7 +244,7 @@ class BoundField(StrAndUnicode): 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) diff --git a/django/newforms/widgets.py b/django/newforms/widgets.py index 5f1a130459..dd71ebc455 100644 --- a/django/newforms/widgets.py +++ b/django/newforms/widgets.py @@ -230,7 +230,7 @@ class RadioInput(StrAndUnicode): 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 @@ class RadioSelect(Select): 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. diff --git a/django/oldforms/__init__.py b/django/oldforms/__init__.py index 873bd0204a..0a4676ee8f 100644 --- a/django/oldforms/__init__.py +++ b/django/oldforms/__init__.py @@ -329,7 +329,7 @@ class FormField(object): 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] diff --git a/django/template/__init__.py b/django/template/__init__.py index a32b3f5a0b..a592765db6 100644 --- a/django/template/__init__.py +++ b/django/template/__init__.py @@ -338,7 +338,7 @@ class Parser(object): 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 diff --git a/django/template/context.py b/django/template/context.py index 25397b0e1a..59650b05fe 100644 --- a/django/template/context.py +++ b/django/template/context.py @@ -35,7 +35,7 @@ class Context(object): 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 @@ class Context(object): 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 @@ class Context(object): 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 diff --git a/django/template/defaulttags.py b/django/template/defaulttags.py index 2deae6d403..1ebb01442e 100644 --- a/django/template/defaulttags.py +++ b/django/template/defaulttags.py @@ -87,7 +87,7 @@ class ForNode(Node): def render(self, context): nodelist = NodeList() - if context.has_key('forloop'): + if 'forloop' in context: parentloop = context['forloop'] else: parentloop = {} @@ -133,7 +133,7 @@ class IfChangedNode(Node): 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) diff --git a/django/utils/datastructures.py b/django/utils/datastructures.py index cca30b462d..60bc0051a2 100644 --- a/django/utils/datastructures.py +++ b/django/utils/datastructures.py @@ -42,7 +42,7 @@ class MergeDict(object): def has_key(self, key): for dict in self.dicts: - if dict.has_key(key): + if key in dict: return True return False diff --git a/django/utils/functional.py b/django/utils/functional.py index e3c0a3c76b..0c31c1f375 100644 --- a/django/utils/functional.py +++ b/django/utils/functional.py @@ -42,7 +42,7 @@ def lazy(func, *resultclasses): 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__ diff --git a/django/utils/translation/trans_real.py b/django/utils/translation/trans_real.py index 0c8dcd540f..293b4ef9cd 100644 --- a/django/utils/translation/trans_real.py +++ b/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(): diff --git a/django/views/i18n.py b/django/views/i18n.py index 0a19cfe986..0fec6b6c6f 100644 --- a/django/views/i18n.py +++ b/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]]) diff --git a/tests/regressiontests/dispatch/tests/test_saferef.py b/tests/regressiontests/dispatch/tests/test_saferef.py index 233a2023e0..c0ec879a4b 100644 --- a/tests/regressiontests/dispatch/tests/test_saferef.py +++ b/tests/regressiontests/dispatch/tests/test_saferef.py @@ -55,8 +55,10 @@ class Tester(unittest.TestCase): 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 diff --git a/tests/regressiontests/httpwrappers/tests.py b/tests/regressiontests/httpwrappers/tests.py index 385c3048d9..29cb8385e0 100644 --- a/tests/regressiontests/httpwrappers/tests.py +++ b/tests/regressiontests/httpwrappers/tests.py @@ -34,6 +34,9 @@ AttributeError: This QueryDict instance is immutable >>> q.has_key('foo') False +>>> 'foo' in q +False + >>> q.items() [] @@ -124,6 +127,9 @@ MultiValueDictKeyError: "Key 'foo' not found in <MultiValueDict: {}>" >>> q.has_key('foo') True +>>> 'foo' in q +True + >>> q.items() [('foo', 'another'), ('name', 'john')] @@ -218,9 +224,15 @@ AttributeError: This QueryDict instance is immutable >>> 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 @@ AttributeError: This QueryDict instance is immutable >>> q.has_key('vote') True +>>> 'vote' in q +True + >>> q.has_key('foo') False +>>> 'foo' in q +False + >>> q.items() [('vote', 'no')]