Skip to content
This repository

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse code

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
Malcolm Tredinnick authored April 26, 2007

Showing 37 changed files with 112 additions and 92 deletions. Show diff stats Hide diff stats

  1. 2  django/bin/profiling/gather_profile_stats.py
  2. 2  django/contrib/admin/templatetags/admin_modify.py
  3. 6  django/contrib/admin/views/auth.py
  4. 10  django/contrib/admin/views/decorators.py
  5. 38  django/contrib/admin/views/main.py
  6. 2  django/contrib/comments/templatetags/comments.py
  7. 12  django/contrib/comments/views/comments.py
  8. 2  django/contrib/sitemaps/views.py
  9. 2  django/core/cache/backends/simple.py
  10. 4  django/core/handlers/modpython.py
  11. 2  django/core/handlers/wsgi.py
  12. 6  django/core/management.py
  13. 12  django/core/servers/basehttp.py
  14. 6  django/core/validators.py
  15. 2  django/db/backends/mysql_old/base.py
  16. 2  django/db/backends/postgresql/base.py
  17. 2  django/db/backends/util.py
  18. 2  django/db/models/fields/__init__.py
  19. 2  django/db/models/fields/generic.py
  20. 4  django/db/models/fields/related.py
  21. 2  django/db/models/loading.py
  22. 4  django/db/models/options.py
  23. 12  django/db/transaction.py
  24. 8  django/http/__init__.py
  25. 2  django/middleware/common.py
  26. 2  django/newforms/forms.py
  27. 4  django/newforms/widgets.py
  28. 2  django/oldforms/__init__.py
  29. 2  django/template/__init__.py
  30. 6  django/template/context.py
  31. 8  django/template/defaulttags.py
  32. 2  django/utils/datastructures.py
  33. 2  django/utils/functional.py
  34. 2  django/utils/translation/trans_real.py
  35. 6  django/views/i18n.py
  36. 2  tests/regressiontests/dispatch/tests/test_saferef.py
  37. 18  tests/regressiontests/httpwrappers/tests.py
2  django/bin/profiling/gather_profile_stats.py
@@ -22,7 +22,7 @@ def gather_stats(p):
22 22
         else:
23 23
             continue
24 24
         print "Processing %s" % f
25  
-        if profiles.has_key(path):
  25
+        if path in profiles:
26 26
             profiles[path].add(prof)
27 27
         else:
28 28
             profiles[path] = prof
2  django/contrib/admin/templatetags/admin_modify.py
@@ -74,7 +74,7 @@ def __init__(self, bound_field_var):
74 74
         self.bound_field_var = bound_field_var
75 75
 
76 76
     def get_nodelist(cls, klass):
77  
-        if not cls.nodelists.has_key(klass):
  77
+        if klass not in cls.nodelists:
78 78
             try:
79 79
                 field_class_name = klass.__name__
80 80
                 template_name = "widget/%s.html" % class_name_to_underscored(field_class_name)
6  django/contrib/admin/views/auth.py
@@ -17,7 +17,7 @@ def user_add_stage(request):
17 17
         if not errors:
18 18
             new_user = manipulator.save(new_data)
19 19
             msg = _('The %(name)s "%(obj)s" was added successfully.') % {'name': 'user', 'obj': new_user}
20  
-            if request.POST.has_key("_addanother"):
  20
+            if "_addanother" in request.POST:
21 21
                 request.user.message_set.create(message=msg)
22 22
                 return HttpResponseRedirect(request.path)
23 23
             else:
@@ -29,7 +29,7 @@ def user_add_stage(request):
29 29
     return render_to_response('admin/auth/user/add_form.html', {
30 30
         'title': _('Add user'),
31 31
         'form': form,
32  
-        'is_popup': request.REQUEST.has_key('_popup'),
  32
+        'is_popup': '_popup' in request.REQUEST,
33 33
         'add': True,
34 34
         'change': False,
35 35
         'has_delete_permission': False,
@@ -63,7 +63,7 @@ def user_change_password(request, id):
63 63
     return render_to_response('admin/auth/user/change_password.html', {
64 64
         'title': _('Change password: %s') % escape(user.username),
65 65
         'form': form,
66  
-        'is_popup': request.REQUEST.has_key('_popup'),
  66
+        'is_popup': '_popup' in request.REQUEST,
67 67
         'add': True,
68 68
         'change': False,
69 69
         'has_delete_permission': False,
10  django/contrib/admin/views/decorators.py
@@ -12,7 +12,7 @@
12 12
 
13 13
 def _display_login_form(request, error_message=''):
14 14
     request.session.set_test_cookie()
15  
-    if request.POST and request.POST.has_key('post_data'):
  15
+    if request.POST and 'post_data' in request.POST:
16 16
         # User has failed login BUT has previously saved post data.
17 17
         post_data = request.POST['post_data']
18 18
     elif request.POST:
@@ -48,7 +48,7 @@ def staff_member_required(view_func):
48 48
     def _checklogin(request, *args, **kwargs):
49 49
         if request.user.is_authenticated() and request.user.is_staff:
50 50
             # The user is valid. Continue to the admin page.
51  
-            if request.POST.has_key('post_data'):
  51
+            if 'post_data' in request.POST:
52 52
                 # User must have re-authenticated through a different window
53 53
                 # or tab.
54 54
                 request.POST = _decode_post_data(request.POST['post_data'])
@@ -57,7 +57,7 @@ def _checklogin(request, *args, **kwargs):
57 57
         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'."
58 58
 
59 59
         # If this isn't already the login page, display it.
60  
-        if not request.POST.has_key(LOGIN_FORM_KEY):
  60
+        if LOGIN_FORM_KEY not in request.POST:
61 61
             if request.POST:
62 62
                 message = _("Please log in again, because your session has expired. Don't worry: Your submission has been saved.")
63 63
             else:
@@ -90,9 +90,9 @@ def _checklogin(request, *args, **kwargs):
90 90
             if user.is_active and user.is_staff:
91 91
                 login(request, user)
92 92
                 # TODO: set last_login with an event.
93  
-                if request.POST.has_key('post_data'):
  93
+                if 'post_data' in request.POST:
94 94
                     post_data = _decode_post_data(request.POST['post_data'])
95  
-                    if post_data and not post_data.has_key(LOGIN_FORM_KEY):
  95
+                    if post_data and LOGIN_FORM_KEY not in post_data:
96 96
                         # overwrite request.POST with the saved post_data, and continue
97 97
                         request.POST = post_data
98 98
                         request.user = user
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
257 257
             msg = _('The %(name)s "%(obj)s" was added successfully.') % {'name': opts.verbose_name, 'obj': new_object}
258 258
             # Here, we distinguish between different save types by checking for
259 259
             # the presence of keys in request.POST.
260  
-            if request.POST.has_key("_continue"):
  260
+            if "_continue" in request.POST:
261 261
                 request.user.message_set.create(message=msg + ' ' + _("You may edit it again below."))
262  
-                if request.POST.has_key("_popup"):
  262
+                if "_popup" in request.POST:
263 263
                     post_url_continue += "?_popup=1"
264 264
                 return HttpResponseRedirect(post_url_continue % pk_value)
265  
-            if request.POST.has_key("_popup"):
  265
+            if "_popup" in request.POST:
266 266
                 if type(pk_value) is str: # Quote if string, so JavaScript doesn't think it's a variable.
267 267
                     pk_value = '"%s"' % pk_value.replace('"', '\\"')
268 268
                 return HttpResponse('<script type="text/javascript">opener.dismissAddAnotherPopup(window, %s, "%s");</script>' % \
269 269
                     (pk_value, str(new_object).replace('"', '\\"')))
270  
-            elif request.POST.has_key("_addanother"):
  270
+            elif "_addanother" in request.POST:
271 271
                 request.user.message_set.create(message=msg + ' ' + (_("You may add another %s below.") % opts.verbose_name))
272 272
                 return HttpResponseRedirect(request.path)
273 273
             else:
@@ -288,7 +288,7 @@ def add_stage(request, app_label, model_name, show_delete=False, form_url='', po
288 288
     c = template.RequestContext(request, {
289 289
         'title': _('Add %s') % opts.verbose_name,
290 290
         'form': form,
291  
-        'is_popup': request.REQUEST.has_key('_popup'),
  291
+        'is_popup': '_popup' in request.REQUEST,
292 292
         'show_delete': show_delete,
293 293
     })
294 294
 
@@ -308,7 +308,7 @@ def change_stage(request, app_label, model_name, object_id):
308 308
     if not request.user.has_perm(app_label + '.' + opts.get_change_permission()):
309 309
         raise PermissionDenied
310 310
 
311  
-    if request.POST and request.POST.has_key("_saveasnew"):
  311
+    if request.POST and "_saveasnew" in request.POST:
312 312
         return add_stage(request, app_label, model_name, form_url='../../add/')
313 313
 
314 314
     try:
@@ -343,16 +343,16 @@ def change_stage(request, app_label, model_name, object_id):
343 343
             LogEntry.objects.log_action(request.user.id, ContentType.objects.get_for_model(model).id, pk_value, str(new_object), CHANGE, change_message)
344 344
 
345 345
             msg = _('The %(name)s "%(obj)s" was changed successfully.') % {'name': opts.verbose_name, 'obj': new_object}
346  
-            if request.POST.has_key("_continue"):
  346
+            if "_continue" in request.POST:
347 347
                 request.user.message_set.create(message=msg + ' ' + _("You may edit it again below."))
348  
-                if request.REQUEST.has_key('_popup'):
  348
+                if '_popup' in request.REQUEST:
349 349
                     return HttpResponseRedirect(request.path + "?_popup=1")
350 350
                 else:
351 351
                     return HttpResponseRedirect(request.path)
352  
-            elif request.POST.has_key("_saveasnew"):
  352
+            elif "_saveasnew" in request.POST:
353 353
                 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})
354 354
                 return HttpResponseRedirect("../%s/" % pk_value)
355  
-            elif request.POST.has_key("_addanother"):
  355
+            elif "_addanother" in request.POST:
356 356
                 request.user.message_set.create(message=msg + ' ' + (_("You may add another %s below.") % opts.verbose_name))
357 357
                 return HttpResponseRedirect("../add/")
358 358
             else:
@@ -392,7 +392,7 @@ def change_stage(request, app_label, model_name, object_id):
392 392
         'form': form,
393 393
         'object_id': object_id,
394 394
         'original': manipulator.original_object,
395  
-        'is_popup': request.REQUEST.has_key('_popup'),
  395
+        'is_popup': '_popup' in request.REQUEST,
396 396
     })
397 397
     return render_change_form(model, manipulator, c, change=True)
398 398
 change_stage = staff_member_required(never_cache(change_stage))
@@ -558,12 +558,12 @@ def __init__(self, request, model):
558 558
             self.page_num = int(request.GET.get(PAGE_VAR, 0))
559 559
         except ValueError:
560 560
             self.page_num = 0
561  
-        self.show_all = request.GET.has_key(ALL_VAR)
562  
-        self.is_popup = request.GET.has_key(IS_POPUP_VAR)
  561
+        self.show_all = ALL_VAR in request.GET
  562
+        self.is_popup = IS_POPUP_VAR in request.GET
563 563
         self.params = dict(request.GET.items())
564  
-        if self.params.has_key(PAGE_VAR):
  564
+        if PAGE_VAR in self.params:
565 565
             del self.params[PAGE_VAR]
566  
-        if self.params.has_key(ERROR_FLAG):
  566
+        if ERROR_FLAG in self.params:
567 567
             del self.params[ERROR_FLAG]
568 568
 
569 569
         self.order_field, self.order_type = self.get_ordering()
@@ -594,7 +594,7 @@ def get_query_string(self, new_params=None, remove=None):
594 594
                 if k.startswith(r):
595 595
                     del p[k]
596 596
         for k, v in new_params.items():
597  
-            if p.has_key(k) and v is None:
  597
+            if k in p and v is None:
598 598
                 del p[k]
599 599
             elif v is not None:
600 600
                 p[k] = v
@@ -656,7 +656,7 @@ def get_ordering(self):
656 656
             order_field, order_type = ordering[0][1:], 'desc'
657 657
         else:
658 658
             order_field, order_type = ordering[0], 'asc'
659  
-        if params.has_key(ORDER_VAR):
  659
+        if ORDER_VAR in params:
660 660
             try:
661 661
                 field_name = lookup_opts.admin.list_display[int(params[ORDER_VAR])]
662 662
                 try:
@@ -674,7 +674,7 @@ def get_ordering(self):
674 674
                         order_field = f.name
675 675
             except (IndexError, ValueError):
676 676
                 pass # Invalid ordering specified. Just use the default.
677  
-        if params.has_key(ORDER_TYPE_VAR) and params[ORDER_TYPE_VAR] in ('asc', 'desc'):
  677
+        if ORDER_TYPE_VAR in params and params[ORDER_TYPE_VAR] in ('asc', 'desc'):
678 678
             order_type = params[ORDER_TYPE_VAR]
679 679
         return order_field, order_type
680 680
 
@@ -682,7 +682,7 @@ def get_query_set(self):
682 682
         qs = self.manager.get_query_set()
683 683
         lookup_params = self.params.copy() # a dictionary of the query string
684 684
         for i in (ALL_VAR, ORDER_VAR, ORDER_TYPE_VAR, SEARCH_VAR, IS_POPUP_VAR):
685  
-            if lookup_params.has_key(i):
  685
+            if i in lookup_params:
686 686
                 del lookup_params[i]
687 687
 
688 688
         # Apply lookup parameters from the query string.
2  django/contrib/comments/templatetags/comments.py
@@ -116,7 +116,7 @@ def render(self, context):
116 116
         comment_list = get_list_function(**kwargs).order_by(self.ordering + 'submit_date').select_related()
117 117
 
118 118
         if not self.free:
119  
-            if context.has_key('user') and context['user'].is_authenticated():
  119
+            if 'user' in context and context['user'].is_authenticated():
120 120
                 user_id = context['user'].id
121 121
                 context['user_can_moderate_comments'] = Comment.objects.user_is_moderator(context['user'])
122 122
             else:
12  django/contrib/comments/views/comments.py
@@ -217,10 +217,10 @@ def post_comment(request):
217 217
     errors = manipulator.get_validation_errors(new_data)
218 218
     # If user gave correct username/password and wasn't already logged in, log them in
219 219
     # so they don't have to enter a username/password again.
220  
-    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']):
  220
+    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']):
221 221
         from django.contrib.auth import login
222 222
         login(request, manipulator.get_user())
223  
-    if errors or request.POST.has_key('preview'):
  223
+    if errors or 'preview' in request.POST:
224 224
         class CommentFormWrapper(oldforms.FormWrapper):
225 225
             def __init__(self, manipulator, new_data, errors, rating_choices):
226 226
                 oldforms.FormWrapper.__init__(self, manipulator, new_data, errors)
@@ -244,7 +244,7 @@ def ratings(self):
244 244
             'rating_range': rating_range,
245 245
             'rating_choices': rating_choices,
246 246
         }, context_instance=RequestContext(request))
247  
-    elif request.POST.has_key('post'):
  247
+    elif 'post' in request.POST:
248 248
         # If the IP is banned, mail the admins, do NOT save the comment, and
249 249
         # serve up the "Thanks for posting" page as if the comment WAS posted.
250 250
         if request.META['REMOTE_ADDR'] in settings.BANNED_IPS:
@@ -298,7 +298,7 @@ def post_free_comment(request):
298 298
     new_data['is_public'] = IS_PUBLIC in option_list
299 299
     manipulator = PublicFreeCommentManipulator()
300 300
     errors = manipulator.get_validation_errors(new_data)
301  
-    if errors or request.POST.has_key('preview'):
  301
+    if errors or 'preview' in request.POST:
302 302
         comment = errors and '' or manipulator.get_comment(new_data)
303 303
         return render_to_response('comments/free_preview.html', {
304 304
             'comment': comment,
@@ -307,7 +307,7 @@ def post_free_comment(request):
307 307
             'target': target,
308 308
             'hash': security_hash,
309 309
         }, context_instance=RequestContext(request))
310  
-    elif request.POST.has_key('post'):
  310
+    elif 'post' in request.POST:
311 311
         # If the IP is banned, mail the admins, do NOT save the comment, and
312 312
         # serve up the "Thanks for posting" page as if the comment WAS posted.
313 313
         if request.META['REMOTE_ADDR'] in settings.BANNED_IPS:
@@ -330,7 +330,7 @@ def comment_was_posted(request):
330 330
             The object the comment was posted on
331 331
     """
332 332
     obj = None
333  
-    if request.GET.has_key('c'):
  333
+    if 'c' in request.GET:
334 334
         content_type_id, object_id = request.GET['c'].split(':')
335 335
         try:
336 336
             content_type = ContentType.objects.get(pk=content_type_id)
2  django/contrib/sitemaps/views.py
@@ -16,7 +16,7 @@ def index(request, sitemaps):
16 16
 def sitemap(request, sitemaps, section=None):
17 17
     maps, urls = [], []
18 18
     if section is not None:
19  
-        if not sitemaps.has_key(section):
  19
+        if section not in sitemaps:
20 20
             raise Http404("No sitemap available for section: %r" % section)
21 21
         maps.append(sitemaps[section])
22 22
     else:
2  django/core/cache/backends/simple.py
@@ -52,7 +52,7 @@ def delete(self, key):
52 52
             pass
53 53
 
54 54
     def has_key(self, key):
55  
-        return self._cache.has_key(key)
  55
+        return key in self._cache
56 56
 
57 57
     def _cull(self):
58 58
         if self._cull_frequency == 0:
4  django/core/handlers/modpython.py
@@ -42,11 +42,11 @@ def get_full_path(self):
42 42
 
43 43
     def is_secure(self):
44 44
         # Note: modpython 3.2.10+ has req.is_https(), but we need to support previous versions
45  
-        return self._req.subprocess_env.has_key('HTTPS') and self._req.subprocess_env['HTTPS'] == 'on'
  45
+        return 'HTTPS' in self._req.subprocess_env and self._req.subprocess_env['HTTPS'] == 'on'
46 46
 
47 47
     def _load_post_and_files(self):
48 48
         "Populates self._post and self._files"
49  
-        if self._req.headers_in.has_key('content-type') and self._req.headers_in['content-type'].startswith('multipart'):
  49
+        if 'content-type' in self._req.headers_in and self._req.headers_in['content-type'].startswith('multipart'):
50 50
             self._post, self._files = http.parse_file_upload(self._req.headers_in, self.raw_post_data)
51 51
         else:
52 52
             self._post, self._files = http.QueryDict(self.raw_post_data), datastructures.MultiValueDict()
2  django/core/handlers/wsgi.py
@@ -103,7 +103,7 @@ def get_full_path(self):
103 103
         return '%s%s' % (self.path, self.environ.get('QUERY_STRING', '') and ('?' + self.environ.get('QUERY_STRING', '')) or '')
104 104
 
105 105
     def is_secure(self):
106  
-        return self.environ.has_key('HTTPS') and self.environ['HTTPS'] == 'on'
  106
+        return 'HTTPS' in self.environ and self.environ['HTTPS'] == 'on'
107 107
 
108 108
     def _load_post_and_files(self):
109 109
         # Populates self._post and self._files
6  django/core/management.py
@@ -314,7 +314,7 @@ def get_sql_delete(app):
314 314
             # Drop the table now
315 315
             output.append('%s %s;' % (style.SQL_KEYWORD('DROP TABLE'),
316 316
                 style.SQL_TABLE(backend.quote_name(model._meta.db_table))))
317  
-            if backend.supports_constraints and references_to_delete.has_key(model):
  317
+            if backend.supports_constraints and model in references_to_delete:
318 318
                 for rel_class, f in references_to_delete[model]:
319 319
                     table = rel_class._meta.db_table
320 320
                     col = f.column
@@ -843,7 +843,7 @@ def inspectdb():
843 843
                 att_name += '_field'
844 844
                 comment_notes.append('Field renamed because it was a Python reserved word.')
845 845
 
846  
-            if relations.has_key(i):
  846
+            if i in relations:
847 847
                 rel_to = relations[i][1] == table_name and "'self'" or table2model(relations[i][1])
848 848
                 field_type = 'ForeignKey(%s' % rel_to
849 849
                 if att_name.endswith('_id'):
@@ -1550,7 +1550,7 @@ def execute_from_command_line(action_mapping=DEFAULT_ACTION_MAPPING, argv=None):
1550 1550
         action = args[0]
1551 1551
     except IndexError:
1552 1552
         parser.print_usage_and_exit()
1553  
-    if not action_mapping.has_key(action):
  1553
+    if action not in action_mapping:
1554 1554
         print_error("Your action, %r, was invalid." % action, argv[0])
1555 1555
 
1556 1556
     # Switch to English, because django-admin.py creates database content
12  django/core/servers/basehttp.py
@@ -208,15 +208,15 @@ def guess_scheme(environ):
208 208
     else:
209 209
         return 'http'
210 210
 
211  
-_hoppish = {
  211
+_hop_headers = {
212 212
     'connection':1, 'keep-alive':1, 'proxy-authenticate':1,
213 213
     'proxy-authorization':1, 'te':1, 'trailers':1, 'transfer-encoding':1,
214 214
     'upgrade':1
215  
-}.has_key
  215
+}
216 216
 
217 217
 def is_hop_by_hop(header_name):
218 218
     """Return true if 'header_name' is an HTTP/1.1 "Hop-by-Hop" header"""
219  
-    return _hoppish(header_name.lower())
  219
+    return header_name.lower() in _hop_headers
220 220
 
221 221
 class ServerHandler(object):
222 222
     """Manage the invocation of a WSGI application"""
@@ -334,7 +334,7 @@ def cleanup_headers(self):
334 334
 
335 335
         Subclasses can extend this to add other defaults.
336 336
         """
337  
-        if not self.headers.has_key('Content-Length'):
  337
+        if 'Content-Length' not in self.headers:
338 338
             self.set_content_length()
339 339
 
340 340
     def start_response(self, status, headers,exc_info=None):
@@ -368,11 +368,11 @@ def send_preamble(self):
368 368
         if self.origin_server:
369 369
             if self.client_is_modern():
370 370
                 self._write('HTTP/%s %s\r\n' % (self.http_version,self.status))
371  
-                if not self.headers.has_key('Date'):
  371
+                if 'Date' not in self.headers:
372 372
                     self._write(
373 373
                         'Date: %s\r\n' % time.asctime(time.gmtime(time.time()))
374 374
                     )
375  
-                if self.server_software and not self.headers.has_key('Server'):
  375
+                if self.server_software and 'Server' not in self.headers:
376 376
                     self._write('Server: %s\r\n' % self.server_software)
377 377
         else:
378 378
             self._write('Status: %s\r\n' % self.status)
6  django/core/validators.py
@@ -284,7 +284,7 @@ def __init__(self, other_field, other_value, validator_list):
284 284
         self.always_test = True
285 285
 
286 286
     def __call__(self, field_data, all_data):
287  
-        if all_data.has_key(self.other_field) and all_data[self.other_field] == self.other_value:
  287
+        if self.other_field in all_data and all_data[self.other_field] == self.other_value:
288 288
             for v in self.validator_list:
289 289
                 v(field_data, all_data)
290 290
 
@@ -322,7 +322,7 @@ def __init__(self, other_field, other_value, error_message=None, other_label=Non
322 322
         self.always_test = True
323 323
 
324 324
     def __call__(self, field_data, all_data):
325  
-        if all_data.has_key(self.other_field) and all_data[self.other_field] == self.other_value and not field_data:
  325
+        if self.other_field in all_data and all_data[self.other_field] == self.other_value and not field_data:
326 326
             raise ValidationError(self.error_message)
327 327
 
328 328
 class RequiredIfOtherFieldDoesNotEqual(object):
@@ -335,7 +335,7 @@ def __init__(self, other_field, other_value, other_label=None, error_message=Non
335 335
         self.always_test = True
336 336
 
337 337
     def __call__(self, field_data, all_data):
338  
-        if all_data.has_key(self.other_field) and all_data[self.other_field] != self.other_value and not field_data:
  338
+        if self.other_field in all_data and all_data[self.other_field] != self.other_value and not field_data:
339 339
             raise ValidationError(self.error_message)
340 340
 
341 341
 class IsLessThanOtherField(object):
2  django/db/backends/mysql_old/base.py
@@ -53,7 +53,7 @@ def executemany(self, sql, param_list):
53 53
             raise Database.Warning, "%s: %s" % (w, self.cursor.fetchall())
54 54
 
55 55
     def __getattr__(self, attr):
56  
-        if self.__dict__.has_key(attr):
  56
+        if attr in self.__dict__:
57 57
             return self.__dict__[attr]
58 58
         else:
59 59
             return getattr(self.cursor, attr)
2  django/db/backends/postgresql/base.py
@@ -48,7 +48,7 @@ def executemany(self, sql, param_list):
48 48
         return self.cursor.executemany(sql, new_param_list)
49 49
 
50 50
     def __getattr__(self, attr):
51  
-        if self.__dict__.has_key(attr):
  51
+        if attr in self.__dict__:
52 52
             return self.__dict__[attr]
53 53
         else:
54 54
             return getattr(self.cursor, attr)
2  django/db/backends/util.py
@@ -33,7 +33,7 @@ def executemany(self, sql, param_list):
33 33
             })
34 34
 
35 35
     def __getattr__(self, attr):
36  
-        if self.__dict__.has_key(attr):
  36
+        if attr in self.__dict__:
37 37
             return self.__dict__[attr]
38 38
         else:
39 39
             return getattr(self.cursor, attr)
2  django/db/models/fields/__init__.py
@@ -779,7 +779,7 @@ def __init__(self, *args, **kwargs):
779 779
         kwargs['maxlength'] = kwargs.get('maxlength', 50)
780 780
         kwargs.setdefault('validator_list', []).append(validators.isSlug)
781 781
         # Set db_index=True unless it's been set manually.
782  
-        if not kwargs.has_key('db_index'):
  782
+        if 'db_index' not in kwargs:
783 783
             kwargs['db_index'] = True
784 784
         Field.__init__(self, *args, **kwargs)
785 785
 
2  django/db/models/fields/generic.py
@@ -37,7 +37,7 @@ def contribute_to_class(self, cls, name):
37 37
     def instance_pre_init(self, signal, sender, args, kwargs):
38 38
         # Handle initalizing an object with the generic FK instaed of 
39 39
         # content-type/object-id fields.        
40  
-        if kwargs.has_key(self.name):
  40
+        if self.name in kwargs:
41 41
             value = kwargs.pop(self.name)
42 42
             kwargs[self.ct_field] = self.get_content_type(value)
43 43
             kwargs[self.fk_field] = value._get_pk_val()
4  django/db/models/fields/related.py
@@ -474,7 +474,7 @@ def __init__(self, to, to_field=None, **kwargs):
@@ -567,7 +567,7 @@ def __init__(self, to, to_field=None, **kwargs):
2  django/db/models/loading.py
@@ -103,7 +103,7 @@ def register_models(app_label, *models):
103 103
         # in the _app_models dictionary
104 104
         model_name = model._meta.object_name.lower()
105 105
         model_dict = _app_models.setdefault(app_label, {})
106  
-        if model_dict.has_key(model_name):
  106
+        if model_name in model_dict:
107 107
             # The same model may be imported via different paths (e.g.
108 108
             # appname.models and project.appname.models). We use the source
109 109
             # filename as a means to detect identity.
4  django/db/models/options.py
@@ -140,7 +140,7 @@ def get_data_holders(self, follow=None):
140 140
     def get_follow(self, override=None):
141 141
         follow = {}
142 142
         for f in self.fields + self.many_to_many + self.get_all_related_objects():
143  
-            if override and override.has_key(f.name):
  143
+            if override and f.name in override:
144 144
                 child_override = override[f.name]
145 145
             else:
146 146
                 child_override = None
@@ -182,7 +182,7 @@ def has_field_type(self, field_type, follow=None):
182 182
         # TODO: follow
183 183
         if not hasattr(self, '_field_types'):
184 184
             self._field_types = {}
185  
-        if not self._field_types.has_key(field_type):
  185
+        if field_type not in self._field_types:
186 186
             try:
187 187
                 # First check self.fields.
188 188
                 for f in self.fields:
12  django/db/transaction.py
@@ -46,12 +46,12 @@ def enter_transaction_management():
46 46
     when no current block is running).
47 47
     """
48 48
     thread_ident = thread.get_ident()
49  
-    if state.has_key(thread_ident) and state[thread_ident]:
  49
+    if thread_ident in state and state[thread_ident]:
50 50
         state[thread_ident].append(state[thread_ident][-1])
51 51
     else:
52 52
         state[thread_ident] = []
53 53
         state[thread_ident].append(settings.TRANSACTIONS_MANAGED)
54  
-    if not dirty.has_key(thread_ident):
  54
+    if thread_ident not in dirty:
55 55
         dirty[thread_ident] = False
56 56
 
57 57
 def leave_transaction_management():
@@ -61,7 +61,7 @@ def leave_transaction_management():
61 61
     those from outside. (Commits are on connection level.)
62 62
     """
63 63
     thread_ident = thread.get_ident()
64  
-    if state.has_key(thread_ident) and state[thread_ident]:
  64
+    if thread_ident in state and state[thread_ident]:
65 65
         del state[thread_ident][-1]
66 66
     else:
67 67
         raise TransactionManagementError("This code isn't under transaction management")
@@ -84,7 +84,7 @@ def set_dirty():
84 84
     changes waiting for commit.
85 85
     """
86 86
     thread_ident = thread.get_ident()
87  
-    if dirty.has_key(thread_ident):
  87
+    if thread_ident in dirty:
88 88
         dirty[thread_ident] = True
89 89
     else:
90 90
         raise TransactionManagementError("This code isn't under transaction management")
@@ -96,7 +96,7 @@ def set_clean():
96 96
     should happen.
97 97
     """
98 98
     thread_ident = thread.get_ident()
99  
-    if dirty.has_key(thread_ident):
  99
+    if thread_ident in dirty:
100 100
         dirty[thread_ident] = False
101 101
     else:
102 102
         raise TransactionManagementError("This code isn't under transaction management")
@@ -106,7 +106,7 @@ def is_managed():
106 106
     Checks whether the transaction manager is in manual or in auto state.
107 107
     """
108 108
     thread_ident = thread.get_ident()
109  
-    if state.has_key(thread_ident):
  109
+    if thread_ident in state:
110 110
         if state[thread_ident]:
111 111
             return state[thread_ident][-1]
112 112
     return settings.TRANSACTIONS_MANAGED
8  django/http/__init__.py
@@ -29,12 +29,12 @@ def __repr__(self):
29 29
 
30 30
     def __getitem__(self, key):
31 31
         for d in (self.POST, self.GET):
32  
-            if d.has_key(key):
  32
+            if key in d:
33 33
                 return d[key]
34 34
         raise KeyError, "%s not found in either POST or GET" % key
35 35
 
36 36
     def has_key(self, key):
37  
-        return self.GET.has_key(key) or self.POST.has_key(key)
  37
+        return key in self.GET or key in self.POST
38 38
 
39 39
     def get_full_path(self):
40 40
         return ''
@@ -57,7 +57,7 @@ def parse_file_upload(header_dict, post_data):
57 57
             # name_dict is something like {'name': 'file', 'filename': 'test.txt'} for file uploads
58 58
             # or {'name': 'blah'} for POST fields
59 59
             # We assume all uploaded files have a 'filename' set.
60  
-            if name_dict.has_key('filename'):
  60
+            if 'filename' in name_dict:
61 61
                 assert type([]) != type(submessage.get_payload()), "Nested MIME messages are not supported"
62 62
                 if not name_dict['filename'].strip():
63 63
                     continue
@@ -66,7 +66,7 @@ def parse_file_upload(header_dict, post_data):
66 66
                 filename = name_dict['filename'][name_dict['filename'].rfind("\\")+1:]
67 67
                 FILES.appendlist(name_dict['name'], {
68 68
                     'filename': filename,
69  
-                    'content-type': (submessage.has_key('Content-Type') and submessage['Content-Type'] or None),
  69
+                    'content-type': 'Content-Type' in submessage and submessage['Content-Type'] or None,
70 70
                     'content': submessage.get_payload(),
71 71
                 })
72 72
             else:
2  django/middleware/common.py
@@ -25,7 +25,7 @@ def process_request(self, request):
25 25
         """
26 26
 
27 27
         # Check for denied User-Agents
28  
-        if request.META.has_key('HTTP_USER_AGENT'):
  28
+        if 'HTTP_USER_AGENT' in request.META:
29 29
             for user_agent_regex in settings.DISALLOWED_USER_AGENTS:
30 30
                 if user_agent_regex.search(request.META['HTTP_USER_AGENT']):
31 31
                     return http.HttpResponseForbidden('<h1>Forbidden</h1>')
2  django/newforms/forms.py
@@ -244,7 +244,7 @@ def _errors(self):
244 244
     def as_widget(self, widget, attrs=None):
245 245
         attrs = attrs or {}
246 246
         auto_id = self.auto_id
247  
-        if auto_id and not attrs.has_key('id') and not widget.attrs.has_key('id'):
  247
+        if auto_id and 'id' not in attrs and 'id' not in widget.attrs:
248 248
             attrs['id'] = auto_id
249 249
         if not self.form.is_bound:
250 250
             data = self.form.initial.get(self.name, self.field.initial)
4  django/newforms/widgets.py
@@ -230,7 +230,7 @@ def is_checked(self):
230 230
         return self.value == self.choice_value
231 231
 
232 232
     def tag(self):
233  
-        if self.attrs.has_key('id'):
  233
+        if 'id' in self.attrs:
234 234
             self.attrs['id'] = '%s_%s' % (self.attrs['id'], self.index)
235 235
         final_attrs = dict(self.attrs, type='radio', name=self.name, value=self.choice_value)
236 236
         if self.is_checked():
@@ -276,7 +276,7 @@ def id_for_label(self, id_):
276 276
 class CheckboxSelectMultiple(SelectMultiple):
277 277
     def render(self, name, value, attrs=None, choices=()):
278 278
         if value is None: value = []
279  
-        has_id = attrs and attrs.has_key('id')
  279
+        has_id = attrs and 'id' in attrs
280 280
         final_attrs = self.build_attrs(attrs, name=name)
281 281
         output = [u'<ul>']
282 282
         str_values = set([smart_unicode(v) for v in value]) # Normalize to strings.
2  django/oldforms/__init__.py
@@ -329,7 +329,7 @@ def extract_data(self, data_dict):
329 329
 
330 330
     def convert_post_data(self, new_data):
331 331
         name = self.get_member_name()
332  
-        if new_data.has_key(self.field_name):
  332
+        if self.field_name in new_data:
333 333
             d = new_data.getlist(self.field_name)
334 334
             try:
335 335
                 converted_data = [self.__class__.html2python(data) for data in d]
2  django/template/__init__.py
@@ -338,7 +338,7 @@ def compile_filter(self, token):
338 338
         return FilterExpression(token, self)
339 339
 
340 340
     def find_filter(self, filter_name):
341  
-        if self.filters.has_key(filter_name):
  341
+        if filter_name in self.filters:
342 342
             return self.filters[filter_name]
343 343
         else:
344 344
             raise TemplateSyntaxError, "Invalid filter: '%s'" % filter_name
6  django/template/context.py
@@ -35,7 +35,7 @@ def __setitem__(self, key, value):
35 35
     def __getitem__(self, key):
36 36
         "Get a variable's value, starting at the current context and going upward"
37 37
         for d in self.dicts:
38  
-            if d.has_key(key):
  38
+            if key in d:
39 39
                 return d[key]
40 40
         raise KeyError(key)
41 41
 
@@ -45,7 +45,7 @@ def __delitem__(self, key):
45 45
 
46 46
     def has_key(self, key):
47 47
         for d in self.dicts:
48  
-            if d.has_key(key):
  48
+            if key in d:
49 49
                 return True
50 50
         return False
51 51
 
@@ -54,7 +54,7 @@ def __contains__(self, key):
54 54
 
55 55
     def get(self, key, otherwise=None):
56 56
         for d in self.dicts:
57  
-            if d.has_key(key):
  57
+            if key in d:
58 58
                 return d[key]
59 59
         return otherwise
60 60
 
8  django/template/defaulttags.py
@@ -87,7 +87,7 @@ def get_nodes_by_type(self, nodetype):
87 87
 
88 88
     def render(self, context):
89 89
         nodelist = NodeList()
90  
-        if context.has_key('forloop'):
  90
+        if 'forloop' in context:
91 91
             parentloop = context['forloop']
92 92
         else:
93 93
             parentloop = {}
@@ -133,7 +133,7 @@ def __init__(self, nodelist, *varlist):
133 133
         self._varlist = varlist
134 134
 
135 135
     def render(self, context):
136  
-        if context.has_key('forloop') and context['forloop']['first']:
  136
+        if 'forloop' in context and context['forloop']['first']:
137 137
             self._last_seen = None
138 138
         try:
139 139
             if self._varlist:
@@ -432,7 +432,7 @@ def cycle(parser, token):
432 432
         name = args[1]
433 433
         if not hasattr(parser, '_namedCycleNodes'):
434 434
             raise TemplateSyntaxError("No named cycles in template: '%s' is not defined" % name)
435  
-        if not parser._namedCycleNodes.has_key(name):
  435
+        if name not in parser._namedCycleNodes:
436 436
             raise TemplateSyntaxError("Named cycle '%s' does not exist" % name)
437 437
         return parser._namedCycleNodes[name]
438 438
 
@@ -911,7 +911,7 @@ def templatetag(parser, token):
911 911
     if len(bits) != 2:
912 912
         raise TemplateSyntaxError, "'templatetag' statement takes one argument"
913 913
     tag = bits[1]
914  
-    if not TemplateTagNode.mapping.has_key(tag):
  914
+    if tag not in TemplateTagNode.mapping:
915 915
         raise TemplateSyntaxError, "Invalid templatetag argument: '%s'. Must be one of: %s" % \
916 916
             (tag, TemplateTagNode.mapping.keys())
917 917
     return TemplateTagNode(tag)
2  django/utils/datastructures.py
@@ -42,7 +42,7 @@ def items(self):
42 42
 
43 43
     def has_key(self, key):
44 44
         for dict in self.dicts:
45  
-            if dict.has_key(key):
  45
+            if key in dict:
46 46
                 return True
47 47
         return False
48 48
 
2  django/utils/functional.py
@@ -42,7 +42,7 @@ def __wrapper__(*args, **kw):
42 42
                 res = self.__func(*self.__args, **self.__kw)
43 43
                 return self.__dispatch[type(res)][funcname](res, *args, **kw)
44 44
 
45  
-            if not self.__dispatch.has_key(klass):
  45
+            if klass not in self.__dispatch:
46 46
                 self.__dispatch[klass] = {}
47 47
             self.__dispatch[klass][funcname] = func
48 48
             return __wrapper__
2  django/utils/translation/trans_real.py
@@ -199,7 +199,7 @@ def deactivate():
199 199
     will resolve against the default translation object, again.
200 200
     """
201 201
     global _active
202  
-    if _active.has_key(currentThread()):
  202
+    if currentThread() in _active:
203 203
         del _active[currentThread()]
204 204
 
205 205
 def get_language():
6  django/views/i18n.py
@@ -97,7 +97,7 @@ def javascript_catalog(request, domain='djangojs', packages=None):
97 97
     deliver your JavaScript source from Django templates.
98 98
     """
99 99
     if request.GET:
100  
-        if request.GET.has_key('language'):
  100
+        if 'language' in request.GET:
101 101
             if check_for_language(request.GET['language']):
102 102
                 activate(request.GET['language'])
103 103
     if packages is None:
@@ -136,7 +136,7 @@ def javascript_catalog(request, domain='djangojs', packages=None):
136 136
                 t.update(catalog._catalog)
137 137
     src = [LibHead]
138 138
     plural = None
139  
-    if t.has_key(''):
  139
+    if '' in t:
140 140
         for l in t[''].split('\n'):
141 141
             if l.startswith('Plural-Forms:'):
142 142
                 plural = l.split(':',1)[1].strip()
@@ -155,7 +155,7 @@ def javascript_catalog(request, domain='djangojs', packages=None):
155 155
         if type(k) in (str, unicode):
156 156
             csrc.append("catalog['%s'] = '%s';\n" % (javascript_quote(k), javascript_quote(v)))
157 157
         elif type(k) == tuple:
158  
-            if not pdict.has_key(k[0]):
  158
+            if k[0] not in pdict:
159 159
                 pdict[k[0]] = k[1]
160 160
             else:
161 161
                 pdict[k[0]] = max(k[1], pdict[k[0]])
2  tests/regressiontests/dispatch/tests/test_saferef.py
@@ -55,8 +55,10 @@ def testShortCircuit (self):
55 55
         for t in self.ts:
56 56
             if hasattr(t, 'x'):
57 57
                 self.assert_(sd.has_key(safeRef(t.x)))
  58
+                self.assert_(safeRef(t.x) in sd)
58 59
             else:
59 60
                 self.assert_(sd.has_key(safeRef(t)))
  61
+                self.assert_(safeRef(t) in sd)
60 62
     
61 63
     def testRepresentation (self):
62 64
         """Test that the reference object's representation works
18  tests/regressiontests/httpwrappers/tests.py
@@ -34,6 +34,9 @@
34 34
 >>> q.has_key('foo')
35 35
 False
36 36
 
  37
+>>> 'foo' in q
  38
+False
  39
+
37 40
 >>> q.items()
38 41
 []
39 42
 
@@ -124,6 +127,9 @@
124 127
 >>> q.has_key('foo')
125 128
 True
126 129
 
  130
+>>> 'foo' in q
  131
+True
  132
+
127 133
 >>> q.items()
128 134
 [('foo', 'another'), ('name', 'john')]
129 135
 
@@ -218,9 +224,15 @@
218 224
 >>> q.has_key('foo')
219 225
 True
220 226
 
  227
+>>> 'foo' in q
  228
+True
  229
+
221 230
 >>> q.has_key('bar')
222 231
 False
223 232
 
  233
+>>> 'bar' in q
  234
+False
  235
+
224 236
 >>> q.items()
225 237
 [('foo', 'bar')]
226 238
 
@@ -303,9 +315,15 @@
303 315
 >>> q.has_key('vote')
304 316
 True
305 317
 
  318
+>>> 'vote' in q
  319
+True
  320
+
306 321
 >>> q.has_key('foo')
307 322
 False
308 323
 
  324
+>>> 'foo' in q
  325
+False
  326
+
309 327
 >>> q.items()
310 328
 [('vote', 'no')]
311 329
 

0 notes on commit 439cb40

Please sign in to comment.
Something went wrong with that request. Please try again.