python: Replace avoidable uses of __special__ attributes.

Signed-off-by: Anders Kaseorg <anders@zulip.com>
This commit is contained in:
Anders Kaseorg
2022-10-07 22:35:48 -07:00
committed by Tim Abbott
parent 73219dd49b
commit fcd81a8473
10 changed files with 27 additions and 27 deletions

View File

@@ -72,7 +72,7 @@ class _RateLimitFilter:
try: try:
# Track duplicate errors # Track duplicate errors
duplicate = False 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: if rate > 0:
(use_cache, should_reset_handling_exception) = self.can_use_remote_cache() (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)) tb = "\n".join(traceback.format_exception(*record.exc_info))
else: else:
tb = str(record) 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 duplicate = cache.get(key) == 1
if not duplicate: if not duplicate:
cache.set(key, 1, rate) cache.set(key, 1, rate)

View File

@@ -26,7 +26,7 @@ def check_config() -> None:
# if required setting is the same as default OR is not found in settings, # if required setting is the same as default OR is not found in settings,
# throw error to add/set that setting in config # throw error to add/set that setting in config
try: try:
if settings.__getattr__(setting_name) != default: if getattr(settings, setting_name) != default:
continue continue
except AttributeError: except AttributeError:
pass pass

View File

@@ -70,7 +70,7 @@ def send_to_push_bouncer(
requests.exceptions.ConnectionError, requests.exceptions.ConnectionError,
) as e: ) as e:
raise PushNotificationBouncerRetryLaterError( 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: if res.status_code >= 500:

View File

@@ -776,7 +776,7 @@ class Realm(models.Model): # type: ignore[django-manager-missing] # django-stub
from zproject.backends import AUTH_BACKEND_NAME_MAP from zproject.backends import AUTH_BACKEND_NAME_MAP
ret: Dict[str, bool] = {} 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 # `authentication_methods` is a bitfield.types.BitHandler, not
# a true dict; since it is still python2- and python3-compat, # a true dict; since it is still python2- and python3-compat,
# `iteritems` is its method to iterate over its contents. # `iteritems` is its method to iterate over its contents.
@@ -2845,7 +2845,7 @@ class AbstractMessage(models.Model):
def __str__(self) -> str: def __str__(self) -> str:
display_recipient = get_display_recipient(self.recipient) 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): class ArchiveTransaction(models.Model):
@@ -3034,7 +3034,7 @@ class Draft(models.Model):
last_edit_time = models.DateTimeField(db_index=True) last_edit_time = models.DateTimeField(db_index=True)
def __str__(self) -> str: 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]: def to_dict(self) -> Dict[str, Any]:
if self.recipient is None: if self.recipient is None:
@@ -3336,7 +3336,7 @@ class UserMessage(AbstractUserMessage):
def __str__(self) -> str: def __str__(self) -> str:
display_recipient = get_display_recipient(self.message.recipient) 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 @staticmethod
def select_for_update_query() -> QuerySet["UserMessage"]: def select_for_update_query() -> QuerySet["UserMessage"]:
@@ -3374,7 +3374,7 @@ class ArchivedUserMessage(AbstractUserMessage):
def __str__(self) -> str: def __str__(self) -> str:
display_recipient = get_display_recipient(self.message.recipient) 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): class AbstractAttachment(models.Model):
@@ -3416,7 +3416,7 @@ class AbstractAttachment(models.Model):
abstract = True abstract = True
def __str__(self) -> str: def __str__(self) -> str:
return f"<{self.__class__.__name__}: {self.file_name}>" return f"<{type(self).__name__}: {self.file_name}>"
class ArchivedAttachment(AbstractAttachment): class ArchivedAttachment(AbstractAttachment):

View File

@@ -1309,7 +1309,7 @@ class MarkdownTest(ZulipTestCase):
) )
linkifier.save() linkifier.save()
self.assertEqual( self.assertEqual(
linkifier.__str__(), str(linkifier),
"<RealmFilter(zulip): #(?P<id>[0-9]{2,8}) https://trac.example.com/ticket/%(id)s>", "<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() linkifier_1.save()
self.assertEqual( self.assertEqual(
linkifier_1.__str__(), str(linkifier_1),
r"<RealmFilter(zulip): (?P<id>ABC\-[0-9]+) https://trac.example.com/ticket/%(id)s>", 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() linkifier_2.save()
self.assertEqual( self.assertEqual(
linkifier_2.__str__(), str(linkifier_2),
r"<RealmFilter(zulip): (?P<id>[A-Z][A-Z0-9]*\-[0-9]+)" r"<RealmFilter(zulip): (?P<id>[A-Z][A-Z0-9]*\-[0-9]+)"
" https://other-trac.example.com/ticket/%(id)s>", " https://other-trac.example.com/ticket/%(id)s>",
) )
@@ -2230,7 +2230,7 @@ class MarkdownTest(ZulipTestCase):
) )
linkifier.save() linkifier.save()
self.assertEqual( self.assertEqual(
linkifier.__str__(), str(linkifier),
"<RealmFilter(zulip): #(?P<id>[0-9]{2,8}) https://trac.example.com/ticket/%(id)s>", "<RealmFilter(zulip): #(?P<id>[0-9]{2,8}) https://trac.example.com/ticket/%(id)s>",
) )
# Create a user that potentially interferes with the pattern. # Create a user that potentially interferes with the pattern.
@@ -2318,7 +2318,7 @@ class MarkdownTest(ZulipTestCase):
) )
linkifier.save() linkifier.save()
self.assertEqual( self.assertEqual(
linkifier.__str__(), str(linkifier),
"<RealmFilter(zulip): #(?P<id>[0-9]{2,8}) https://trac.example.com/ticket/%(id)s>", "<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. # Create a user-group that potentially interferes with the pattern.
@@ -2576,7 +2576,7 @@ class MarkdownTest(ZulipTestCase):
) )
linkifier.save() linkifier.save()
self.assertEqual( self.assertEqual(
linkifier.__str__(), str(linkifier),
"<RealmFilter(zulip): #(?P<id>[0-9]{2,8}) https://trac.example.com/ticket/%(id)s>", "<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. # Create a topic link that potentially interferes with the pattern.
@@ -2645,7 +2645,7 @@ class MarkdownTest(ZulipTestCase):
) )
linkifier.save() linkifier.save()
self.assertEqual( self.assertEqual(
linkifier.__str__(), str(linkifier),
"<RealmFilter(zulip): #(?P<id>[0-9]{2,8}) https://trac.example.com/ticket/%(id)s>", "<RealmFilter(zulip): #(?P<id>[0-9]{2,8}) https://trac.example.com/ticket/%(id)s>",
) )
# Create a stream that potentially interferes with the pattern. # Create a stream that potentially interferes with the pattern.

View File

@@ -258,7 +258,7 @@ class MessageDictTest(ZulipTestCase):
realm=zulip_realm, pattern=r"#(?P<id>[0-9]{2,8})", url_format_string=url_format_string realm=zulip_realm, pattern=r"#(?P<id>[0-9]{2,8})", url_format_string=url_format_string
) )
self.assertEqual( self.assertEqual(
linkifier.__str__(), str(linkifier),
"<RealmFilter(zulip): #(?P<id>[0-9]{2,8}) https://trac.example.com/ticket/%(id)s>", "<RealmFilter(zulip): #(?P<id>[0-9]{2,8}) https://trac.example.com/ticket/%(id)s>",
) )

View File

@@ -110,7 +110,7 @@ class AsyncDjangoHandler(tornado.web.RequestHandler):
# `get_response()`. # `get_response()`.
set_script_prefix(get_script_name(environ)) set_script_prefix(get_script_name(environ))
await sync_to_async( 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, thread_sensitive=True,
)() )()
self._request = WSGIRequest(environ) self._request = WSGIRequest(environ)

View File

@@ -377,8 +377,8 @@ def finish_mobile_flow(request: HttpRequest, user_profile: UserProfile, otp: str
# automatically. So we call it manually here. # automatically. So we call it manually here.
# #
# Arguably, sending a fake 'user_logged_in' signal would be a better approach: # 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) # user_logged_in.send(sender=type(user_profile), request=request, user=user_profile)
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. # Mark this request as having a logged-in user for our server logs.
process_client(request, user_profile) process_client(request, user_profile)
@@ -916,11 +916,11 @@ def api_fetch_api_key(
assert user_profile.is_authenticated assert user_profile.is_authenticated
# Maybe sending 'user_logged_in' signal is the better approach: # 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 # 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 # in the session. If the signal receiver assumes that we do then that
# would cause problems. # 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. # Mark this request as having a logged-in user for our server logs.
assert isinstance(user_profile, UserProfile) assert isinstance(user_profile, UserProfile)

View File

@@ -197,7 +197,7 @@ def retry_send_email_failures(
socket.timeout, socket.timeout,
EmailNotDeliveredException, EmailNotDeliveredException,
) as e: ) as e:
error_class_name = e.__class__.__name__ error_class_name = type(e).__name__
def on_failure(event: Dict[str, Any]) -> None: def on_failure(event: Dict[str, Any]) -> None:
logging.exception( logging.exception(

View File

@@ -897,7 +897,7 @@ class ZulipLDAPAuthBackend(ZulipLDAPAuthBackendBase):
# django-auth-ldap authenticate(). # django-auth-ldap authenticate().
username = self.django_to_ldap_username(username) username = self.django_to_ldap_username(username)
except ZulipLDAPExceptionNoMatchingLDAPUser as e: 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: if return_data is not None:
return_data["no_matching_ldap_user"] = True return_data["no_matching_ldap_user"] = True
return None return None
@@ -1103,7 +1103,7 @@ def catch_ldap_error(signal: Signal, **kwargs: Any) -> None:
if kwargs["context"] == "populate_user": if kwargs["context"] == "populate_user":
# The exception message can contain the password (if it was invalid), # 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. # 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: 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), # the flow or the IdP is unreliable and returns a bad http response),
# don't throw a 500, just send them back to the # don't throw a 500, just send them back to the
# login page and record the event at the info log level. # 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 return None
except SocialAuthBaseException as e: except SocialAuthBaseException as e:
# Other python-social-auth exceptions are likely # Other python-social-auth exceptions are likely