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:
# 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)

View File

@@ -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

View File

@@ -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:

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
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):

View File

@@ -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.

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
)
self.assertEqual(
linkifier.__str__(),
str(linkifier),
"<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()`.
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)

View File

@@ -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)

View File

@@ -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(

View File

@@ -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