Opened 7 years ago

Closed 7 years ago

#28985 closed Cleanup/optimization (fixed)

Remove None checking before hasattr()

Reported by: Дилян Палаузов Owned by: nobody
Component: Core (Other) Version: dev
Severity: Normal Keywords:
Cc: Triage Stage: Ready for checkin
Has patch: yes Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: no UI/UX: no

Description

diff --git a/django/contrib/admin/utils.py b/django/contrib/admin/utils.py
--- a/django/contrib/admin/utils.py
+++ b/django/contrib/admin/utils.py
@@ -281,7 +281,7 @@ def lookup_field(name, obj, model_admin=None):
         if callable(name):
             attr = name
             value = attr(obj)
-        elif model_admin is not None and hasattr(model_admin, name) and name != '__str__':
+        elif hasattr(model_admin, name) and name != '__str__':
             attr = getattr(model_admin, name)
             value = attr(obj)
         else:
@@ -341,7 +341,7 @@ def label_for_field(name, model, model_admin=None, return_attr=False):
         else:
             if callable(name):
                 attr = name
-            elif model_admin is not None and hasattr(model_admin, name):
+            elif hasattr(model_admin, name):
                 attr = getattr(model_admin, name)
             elif hasattr(model, name):
                 attr = getattr(model, name)
diff --git a/django/contrib/auth/__init__.py b/django/contrib/auth/__init__.py
--- a/django/contrib/auth/__init__.py
+++ b/django/contrib/auth/__init__.py
@@ -137,7 +137,7 @@ def logout(request):
     # Dispatch the signal before the user is logged out so the receivers have a
     # chance to find out *who* logged out.
     user = getattr(request, 'user', None)
-    if hasattr(user, 'is_authenticated') and not user.is_authenticated:
+    if not getattr(user, 'is_authenticated', True):
         user = None
     user_logged_out.send(sender=user.__class__, request=request, user=user)

diff --git a/django/db/models/fields/files.py b/django/db/models/fields/files.py
--- a/django/db/models/fields/files.py
+++ b/django/db/models/fields/files.py
@@ -70,10 +70,10 @@ class FieldFile(File):
 
     def open(self, mode='rb'):
         self._require_file()
-        if hasattr(self, '_file') and self._file is not None:
-            self.file.open(mode)
-        else:
+        if getattr(self, '_file', None) is None:
             self.file = self.storage.open(self.name, mode)
+        else:
+            self.file.open(mode)
         return self
     # open() doesn't alter the file's contents, but it does reset the pointer
     open.alters_data = True
diff --git a/django/forms/models.py b/django/forms/models.py
--- a/django/forms/models.py
+++ b/django/forms/models.py
@@ -1349,8 +1349,7 @@ class ModelMultipleChoiceField(ModelChoiceField):
 
 
 def modelform_defines_fields(form_class):
-    return (form_class is not None and (
-            hasattr(form_class, '_meta') and
+    return (hasattr(form_class, '_meta') and
             (form_class._meta.fields is not None or
              form_class._meta.exclude is not None)
-            ))
+            )
diff --git a/django/test/html.py b/django/test/html.py
--- a/django/test/html.py
+++ b/django/test/html.py
@@ -52,9 +52,7 @@ class Element:
                 child.finalize()
 
     def __eq__(self, element):
-        if not hasattr(element, 'name'):
-            return False
-        if hasattr(element, 'name') and self.name != element.name:
+        if not hasattr(element, 'name') or self.name != element.name:
             return False
         if len(self.attributes) != len(element.attributes):
             return False
diff --git a/django/views/debug.py b/django/views/debug.py
--- a/django/views/debug.py
+++ b/django/views/debug.py
@@ -346,7 +346,7 @@ class ExceptionReporter:
         Return (pre_context_lineno, pre_context, context_line, post_context).
         """
         source = None
-        if loader is not None and hasattr(loader, "get_source"):
+        if hasattr(loader, "get_source"):
             try:
                 source = loader.get_source(module_name)
             except ImportError:
diff --git a/django/views/generic/detail.py b/django/views/generic/detail.py
--- a/django/views/generic/detail.py
+++ b/django/views/generic/detail.py
@@ -144,7 +144,7 @@ class SingleObjectTemplateResponseMixin(TemplateResponseMixin):
                     object_meta.model_name,
                     self.template_name_suffix
                 ))
-            elif hasattr(self, 'model') and self.model is not None and issubclass(self.model, models.Model):
+            elif getattr(self, 'model', None) is not None and issubclass(self.model, models.Model):
                 names.append("%s/%s%s.html" % (
                     self.model._meta.app_label,
                     self.model._meta.model_name,
diff --git a/django/views/generic/edit.py b/django/views/generic/edit.py
--- a/django/views/generic/edit.py
+++ b/django/views/generic/edit.py
@@ -83,7 +83,7 @@ class ModelFormMixin(FormMixin, SingleObjectMixin):
             if self.model is not None:
                 # If a model has been explicitly provided, use it
                 model = self.model
-            elif hasattr(self, 'object') and self.object is not None:
+            elif getattr(self, 'object', None) is not None:
                 # If this view is operating on a single object, use
                 # the class of that object
                 model = self.object.__class__

Change History (2)

comment:1 by Tim Graham, 7 years ago

Component: UncategorizedCore (Other)
Summary: Remove tautology with None and hasattr()Remove None checking before hasattr()
Triage Stage: UnreviewedReady for checkin

comment:2 by Tim Graham <timograham@…>, 7 years ago

Resolution: fixed
Status: newclosed

In d79cf1e9:

Fixed #28985 -- Removed unneeded None checks before hasattr().

Note: See TracTickets for help on using tickets.
Back to Top