Skip to content

armgit / zulip

Public Imported from GitHub
0

Zulip server and web application. Open-source team chat that helps teams stay productive and focused.

python: Replace avoidable uses of __special__ attributes.

Anders Kaseorgfcd81a8473dd
diff --git a/zerver/lib/logging_util.py b/zerver/lib/logging_util.py
index b796ed67349..030cf937200 100644
--- a/zerver/lib/logging_util.py
+++ b/zerver/lib/logging_util.py
@@ -72,7 +72,7 @@ class _RateLimitFilter:
try:
# Track duplicate errors
duplicate = False
- rate = getattr(settings, f"{self.__class__.__name__.upper()}_LIMIT", 600) # seconds
+ rate = getattr(settings, f"{type(self).__name__.upper()}_LIMIT", 600) # seconds
if rate > 0:
(use_cache, should_reset_handling_exception) = self.can_use_remote_cache()
@@ -81,7 +81,7 @@ class _RateLimitFilter:
tb = "\n".join(traceback.format_exception(*record.exc_info))
else:
tb = str(record)
- key = self.__class__.__name__.upper() + hashlib.sha1(tb.encode()).hexdigest()
+ key = type(self).__name__.upper() + hashlib.sha1(tb.encode()).hexdigest()
duplicate = cache.get(key) == 1
if not duplicate:
cache.set(key, 1, rate)
diff --git a/zerver/lib/management.py b/zerver/lib/management.py
index 24a4a9c2f3c..579fb177fe7 100644
--- a/zerver/lib/management.py
+++ b/zerver/lib/management.py
@@ -26,7 +26,7 @@ def check_config() -> None:
# if required setting is the same as default OR is not found in settings,
# throw error to add/set that setting in config
try:
- if settings.__getattr__(setting_name) != default:
+ if getattr(settings, setting_name) != default:
continue
except AttributeError:
pass
diff --git a/zerver/lib/remote_server.py b/zerver/lib/remote_server.py
index e445217850e..62fa3df1453 100644
--- a/zerver/lib/remote_server.py
+++ b/zerver/lib/remote_server.py
@@ -70,7 +70,7 @@ def send_to_push_bouncer(
requests.exceptions.ConnectionError,
) as e:
raise PushNotificationBouncerRetryLaterError(
- f"{e.__class__.__name__} while trying to connect to push notification bouncer"
+ f"{type(e).__name__} while trying to connect to push notification bouncer"
)
if res.status_code >= 500:
diff --git a/zerver/models.py b/zerver/models.py
index 5485ee8fa93..cb6c429d226 100644
--- a/zerver/models.py
+++ b/zerver/models.py
@@ -776,7 +776,7 @@ class Realm(models.Model): # type: ignore[django-manager-missing] # django-stub
from zproject.backends import AUTH_BACKEND_NAME_MAP
ret: Dict[str, bool] = {}
- supported_backends = [backend.__class__ for backend in supported_auth_backends()]
+ supported_backends = [type(backend) for backend in supported_auth_backends()]
# `authentication_methods` is a bitfield.types.BitHandler, not
# a true dict; since it is still python2- and python3-compat,
# `iteritems` is its method to iterate over its contents.
@@ -2845,7 +2845,7 @@ class AbstractMessage(models.Model):
def __str__(self) -> str:
display_recipient = get_display_recipient(self.recipient)
- return f"<{self.__class__.__name__}: {display_recipient} / {self.subject} / {self.sender}>"
+ return f"<{type(self).__name__}: {display_recipient} / {self.subject} / {self.sender}>"
class ArchiveTransaction(models.Model):
@@ -3034,7 +3034,7 @@ class Draft(models.Model):
last_edit_time = models.DateTimeField(db_index=True)
def __str__(self) -> str:
- return f"<{self.__class__.__name__}: {self.user_profile.email} / {self.id} / {self.last_edit_time}>"
+ return f"<{type(self).__name__}: {self.user_profile.email} / {self.id} / {self.last_edit_time}>"
def to_dict(self) -> Dict[str, Any]:
if self.recipient is None:
@@ -3336,7 +3336,7 @@ class UserMessage(AbstractUserMessage):
def __str__(self) -> str:
display_recipient = get_display_recipient(self.message.recipient)
- return f"<{self.__class__.__name__}: {display_recipient} / {self.user_profile.email} ({self.flags_list()})>"
+ return f"<{type(self).__name__}: {display_recipient} / {self.user_profile.email} ({self.flags_list()})>"
@staticmethod
def select_for_update_query() -> QuerySet["UserMessage"]:
@@ -3374,7 +3374,7 @@ class ArchivedUserMessage(AbstractUserMessage):
def __str__(self) -> str:
display_recipient = get_display_recipient(self.message.recipient)
- return f"<{self.__class__.__name__}: {display_recipient} / {self.user_profile.email} ({self.flags_list()})>"
+ return f"<{type(self).__name__}: {display_recipient} / {self.user_profile.email} ({self.flags_list()})>"
class AbstractAttachment(models.Model):
@@ -3416,7 +3416,7 @@ class AbstractAttachment(models.Model):
abstract = True
def __str__(self) -> str:
- return f"<{self.__class__.__name__}: {self.file_name}>"
+ return f"<{type(self).__name__}: {self.file_name}>"
class ArchivedAttachment(AbstractAttachment):
diff --git a/zerver/tests/test_markdown.py b/zerver/tests/test_markdown.py
index 7407568f590..5f43464c45d 100644
--- a/zerver/tests/test_markdown.py
+++ b/zerver/tests/test_markdown.py
@@ -1309,7 +1309,7 @@ class MarkdownTest(ZulipTestCase):
)
linkifier.save()
self.assertEqual(
- linkifier.__str__(),
+ str(linkifier),
"<RealmFilter(zulip): #(?P<id>[0-9]{2,8}) https://trac.example.com/ticket/%(id)s>",
)
@@ -1447,7 +1447,7 @@ class MarkdownTest(ZulipTestCase):
)
linkifier_1.save()
self.assertEqual(
- linkifier_1.__str__(),
+ str(linkifier_1),
r"<RealmFilter(zulip): (?P<id>ABC\-[0-9]+) https://trac.example.com/ticket/%(id)s>",
)
@@ -1459,7 +1459,7 @@ class MarkdownTest(ZulipTestCase):
)
linkifier_2.save()
self.assertEqual(
- linkifier_2.__str__(),
+ str(linkifier_2),
r"<RealmFilter(zulip): (?P<id>[A-Z][A-Z0-9]*\-[0-9]+)"
" https://other-trac.example.com/ticket/%(id)s>",
)
@@ -2230,7 +2230,7 @@ class MarkdownTest(ZulipTestCase):
)
linkifier.save()
self.assertEqual(
- linkifier.__str__(),
+ str(linkifier),
"<RealmFilter(zulip): #(?P<id>[0-9]{2,8}) https://trac.example.com/ticket/%(id)s>",
)
# Create a user that potentially interferes with the pattern.
@@ -2318,7 +2318,7 @@ class MarkdownTest(ZulipTestCase):
)
linkifier.save()
self.assertEqual(
- linkifier.__str__(),
+ str(linkifier),
"<RealmFilter(zulip): #(?P<id>[0-9]{2,8}) https://trac.example.com/ticket/%(id)s>",
)
# Create a user-group that potentially interferes with the pattern.
@@ -2576,7 +2576,7 @@ class MarkdownTest(ZulipTestCase):
)
linkifier.save()
self.assertEqual(
- linkifier.__str__(),
+ str(linkifier),
"<RealmFilter(zulip): #(?P<id>[0-9]{2,8}) https://trac.example.com/ticket/%(id)s>",
)
# Create a topic link that potentially interferes with the pattern.
@@ -2645,7 +2645,7 @@ class MarkdownTest(ZulipTestCase):
)
linkifier.save()
self.assertEqual(
- linkifier.__str__(),
+ str(linkifier),
"<RealmFilter(zulip): #(?P<id>[0-9]{2,8}) https://trac.example.com/ticket/%(id)s>",
)
# Create a stream that potentially interferes with the pattern.
diff --git a/zerver/tests/test_message_dict.py b/zerver/tests/test_message_dict.py
index 6dca7ef6bd4..c034f15ef07 100644
--- a/zerver/tests/test_message_dict.py
+++ b/zerver/tests/test_message_dict.py
@@ -258,7 +258,7 @@ class MessageDictTest(ZulipTestCase):
realm=zulip_realm, pattern=r"#(?P<id>[0-9]{2,8})", url_format_string=url_format_string
)
self.assertEqual(
- linkifier.__str__(),
+ str(linkifier),
"<RealmFilter(zulip): #(?P<id>[0-9]{2,8}) https://trac.example.com/ticket/%(id)s>",
)
diff --git a/zerver/tornado/handlers.py b/zerver/tornado/handlers.py
index 1c3d72d9792..f52b3b794cf 100644
--- a/zerver/tornado/handlers.py
+++ b/zerver/tornado/handlers.py
@@ -110,7 +110,7 @@ class AsyncDjangoHandler(tornado.web.RequestHandler):
# `get_response()`.
set_script_prefix(get_script_name(environ))
await sync_to_async(
- lambda: signals.request_started.send(sender=self.django_handler.__class__),
+ lambda: signals.request_started.send(sender=type(self.django_handler)),
thread_sensitive=True,
)()
self._request = WSGIRequest(environ)
diff --git a/zerver/views/auth.py b/zerver/views/auth.py
index 32381123b3a..dec150e3b98 100644
--- a/zerver/views/auth.py
+++ b/zerver/views/auth.py
@@ -377,8 +377,8 @@ def finish_mobile_flow(request: HttpRequest, user_profile: UserProfile, otp: str
# automatically. So we call it manually here.
#
# Arguably, sending a fake 'user_logged_in' signal would be a better approach:
- # user_logged_in.send(sender=user_profile.__class__, request=request, user=user_profile)
- email_on_new_login(sender=user_profile.__class__, request=request, user=user_profile)
+ # user_logged_in.send(sender=type(user_profile), request=request, user=user_profile)
+ email_on_new_login(sender=type(user_profile), request=request, user=user_profile)
# Mark this request as having a logged-in user for our server logs.
process_client(request, user_profile)
@@ -916,11 +916,11 @@ def api_fetch_api_key(
assert user_profile.is_authenticated
# Maybe sending 'user_logged_in' signal is the better approach:
- # user_logged_in.send(sender=user_profile.__class__, request=request, user=user_profile)
+ # user_logged_in.send(sender=type(user_profile), request=request, user=user_profile)
# Not doing this only because over here we don't add the user information
# in the session. If the signal receiver assumes that we do then that
# would cause problems.
- email_on_new_login(sender=user_profile.__class__, request=request, user=user_profile)
+ email_on_new_login(sender=type(user_profile), request=request, user=user_profile)
# Mark this request as having a logged-in user for our server logs.
assert isinstance(user_profile, UserProfile)
diff --git a/zerver/worker/queue_processors.py b/zerver/worker/queue_processors.py
index d7fa345649e..5131de2792a 100644
--- a/zerver/worker/queue_processors.py
+++ b/zerver/worker/queue_processors.py
@@ -197,7 +197,7 @@ def retry_send_email_failures(
socket.timeout,
EmailNotDeliveredException,
) as e:
- error_class_name = e.__class__.__name__
+ error_class_name = type(e).__name__
def on_failure(event: Dict[str, Any]) -> None:
logging.exception(
diff --git a/zproject/backends.py b/zproject/backends.py
index 0f955d5b9d4..6e9827b53cc 100644
--- a/zproject/backends.py
+++ b/zproject/backends.py
@@ -897,7 +897,7 @@ class ZulipLDAPAuthBackend(ZulipLDAPAuthBackendBase):
# django-auth-ldap authenticate().
username = self.django_to_ldap_username(username)
except ZulipLDAPExceptionNoMatchingLDAPUser as e:
- ldap_logger.debug("%s: %s", self.__class__.__name__, e)
+ ldap_logger.debug("%s: %s", type(self).__name__, e)
if return_data is not None:
return_data["no_matching_ldap_user"] = True
return None
@@ -1103,7 +1103,7 @@ def catch_ldap_error(signal: Signal, **kwargs: Any) -> None:
if kwargs["context"] == "populate_user":
# The exception message can contain the password (if it was invalid),
# so it seems better not to log that, and only use the original exception's name here.
- raise PopulateUserLDAPError(kwargs["exception"].__class__.__name__)
+ raise PopulateUserLDAPError(type(kwargs["exception"]).__name__)
def sync_user_from_ldap(user_profile: UserProfile, logger: logging.Logger) -> bool:
@@ -1822,7 +1822,7 @@ class SocialAuthMixin(ZulipAuthMixin, ExternalAuthMethod, BaseAuth):
# the flow or the IdP is unreliable and returns a bad http response),
# don't throw a 500, just send them back to the
# login page and record the event at the info log level.
- self.logger.info("%s: %s", e.__class__.__name__, str(e))
+ self.logger.info("%s: %s", type(e).__name__, str(e))
return None
except SocialAuthBaseException as e:
# Other python-social-auth exceptions are likely