Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 4 additions & 8 deletions accounting/api/account.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,8 +23,7 @@ def get_all(request):
})
def get_one(request, account_id: int):
try:
account = Account.objects.get(id=account_id)
return account
return Account.objects.get(id=account_id)
Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function get_one refactored with the following changes:

except Account.DoesNotExist:
return 404, {'detail': f'Account with id {account_id} does not exist'}

Expand All @@ -48,12 +47,9 @@ def get_account_balance(request, account_id: int):
@account_router.get('/account-balances/', response=List[GeneralLedgerOut])
def get_account_balances(request):
accounts = Account.objects.all()
result = []
for a in accounts:
result.append({
'account': a.name, 'balance': list(a.balance())
})

result = [
{'account': a.name, 'balance': list(a.balance())} for a in accounts
]
Comment on lines -51 to +52
Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function get_account_balances refactored with the following changes:

return status.HTTP_200_OK, result


Expand Down
2 changes: 1 addition & 1 deletion restauth/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@

class EmailAccountManager(UserManager):
def get_by_natural_key(self, username):
case_insensitive_username_field = '{}__iexact'.format(self.model.USERNAME_FIELD)
case_insensitive_username_field = f'{self.model.USERNAME_FIELD}__iexact'
Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function EmailAccountManager.get_by_natural_key refactored with the following changes:

return self.get(**{case_insensitive_username_field: username})

def create_user(self, first_name, last_name, email, password=None):
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,11 +15,10 @@ def is_double_callable(application):
if inspect.isclass(application):
return True
# Instanted classes depend on their __call__
if hasattr(application, "__call__"):
# We only check to see if its __call__ is a coroutine function -
# if it's not, it still might be a coroutine function itself.
if asyncio.iscoroutinefunction(application.__call__):
return False
if hasattr(application, "__call__") and asyncio.iscoroutinefunction(
application.__call__
):
return False
Comment on lines -18 to +21
Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function is_double_callable refactored with the following changes:

This removes the following comments ( why? ):

# if it's not, it still might be a coroutine function itself.
# We only check to see if its __call__ is a coroutine function -

# Non-classes we just check directly
return not asyncio.iscoroutinefunction(application)

Expand Down
5 changes: 1 addition & 4 deletions unicoding_venv/lib/python3.9/site-packages/asgiref/local.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,10 +36,7 @@ def __init__(self, thread_critical: bool = False) -> None:
self._context_refs: "weakref.WeakSet[object]" = weakref.WeakSet()
# Random suffixes stop accidental reuse between different Locals,
# though we try to force deletion as well.
self._attr_name = "_asgiref_local_impl_{}_{}".format(
id(self),
"".join(random.choice(string.ascii_letters) for i in range(8)),
)
self._attr_name = f'_asgiref_local_impl_{id(self)}_{"".join(random.choice(string.ascii_letters) for _ in range(8))}'
Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function Local.__init__ refactored with the following changes:


def _get_context_id(self):
"""
Expand Down
3 changes: 1 addition & 2 deletions unicoding_venv/lib/python3.9/site-packages/asgiref/server.py
Original file line number Diff line number Diff line change
Expand Up @@ -136,8 +136,7 @@ async def application_checker(self):
await asyncio.sleep(self.application_checker_interval)
for scope_id, details in list(self.application_instances.items()):
if details["future"].done():
exception = details["future"].exception()
if exception:
if exception := details["future"].exception():
Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function StatelessServer.application_checker refactored with the following changes:

await self.application_exception(exception, details)
try:
del self.application_instances[scope_id]
Expand Down
22 changes: 8 additions & 14 deletions unicoding_venv/lib/python3.9/site-packages/asgiref/sync.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,15 +30,13 @@ def _iscoroutinefunction_or_partial(func: Any) -> bool:
# Python < 3.8 does not correctly determine partially wrapped
# coroutine functions are coroutine functions, hence the need for
# this to exist. Code taken from CPython.
if sys.version_info >= (3, 8):
return asyncio.iscoroutinefunction(func)
else:
if sys.version_info < (3, 8):
while inspect.ismethod(func):
func = func.__func__
while isinstance(func, functools.partial):
func = func.func

return asyncio.iscoroutinefunction(func)
return asyncio.iscoroutinefunction(func)
Comment on lines -33 to +39
Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function _iscoroutinefunction_or_partial refactored with the following changes:



class ThreadSensitiveContext:
Expand Down Expand Up @@ -76,8 +74,7 @@ async def __aexit__(self, exc, value, tb):
if not self.token:
return

executor = SyncToAsync.context_to_thread_executor.pop(self, None)
if executor:
if executor := SyncToAsync.context_to_thread_executor.pop(self, None):
Comment on lines -79 to +77
Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function ThreadSensitiveContext.__aexit__ refactored with the following changes:

executor.shutdown()
SyncToAsync.thread_sensitive_context.reset(self.token)

Expand Down Expand Up @@ -465,14 +462,11 @@ def thread_handler(self, loop, source_task, exc_info, func, *args, **kwargs):
parent_set = True
# Run the function
try:
# If we have an exception, run the function inside the except block
# after raising it so exc_info is correctly populated.
if exc_info[1]:
try:
raise exc_info[1]
except BaseException:
return func(*args, **kwargs)
else:
if not exc_info[1]:
return func(*args, **kwargs)
try:
raise exc_info[1]
except BaseException:
Comment on lines -468 to +469
Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function SyncToAsync.thread_handler refactored with the following changes:

This removes the following comments ( why? ):

# If we have an exception, run the function inside the except block
# after raising it so exc_info is correctly populated.

return func(*args, **kwargs)
finally:
# Only delete the launch_map parent if we set it, otherwise it is
Expand Down
10 changes: 6 additions & 4 deletions unicoding_venv/lib/python3.9/site-packages/asgiref/wsgi.py
Original file line number Diff line number Diff line change
Expand Up @@ -56,10 +56,12 @@ def build_environ(self, scope, body):
"""
environ = {
"REQUEST_METHOD": scope["method"],
"SCRIPT_NAME": scope.get("root_path", "").encode("utf8").decode("latin1"),
"SCRIPT_NAME": scope.get("root_path", "")
.encode("utf8")
.decode("latin1"),
"PATH_INFO": scope["path"].encode("utf8").decode("latin1"),
"QUERY_STRING": scope["query_string"].decode("ascii"),
"SERVER_PROTOCOL": "HTTP/%s" % scope["http_version"],
"SERVER_PROTOCOL": f'HTTP/{scope["http_version"]}',
Comment on lines -59 to +64
Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function WsgiToAsgiInstance.build_environ refactored with the following changes:

"wsgi.version": (1, 0),
"wsgi.url_scheme": scope.get("scheme", "http"),
"wsgi.input": body,
Expand Down Expand Up @@ -87,11 +89,11 @@ def build_environ(self, scope, body):
elif name == "content-type":
corrected_name = "CONTENT_TYPE"
else:
corrected_name = "HTTP_%s" % name.upper().replace("-", "_")
corrected_name = f'HTTP_{name.upper().replace("-", "_")}'
# HTTPbis say only ASCII chars are allowed in headers, but we latin1 just in case
value = value.decode("latin1")
if corrected_name in environ:
value = environ[corrected_name] + "," + value
value = f"{environ[corrected_name]},{value}"
environ[corrected_name] = value
return environ

Expand Down
17 changes: 5 additions & 12 deletions unicoding_venv/lib/python3.9/site-packages/django/apps/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ def __init__(self, app_name, app_module):
self.label = app_name.rpartition(".")[2]
if not self.label.isidentifier():
raise ImproperlyConfigured(
"The app label '%s' is not a valid Python identifier." % self.label
f"The app label '{self.label}' is not a valid Python identifier."
Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function AppConfig.__init__ refactored with the following changes:

)

# Human-readable name for the application e.g. "Admin".
Expand All @@ -58,7 +58,7 @@ def __init__(self, app_name, app_module):
self.models = None

def __repr__(self):
return "<%s: %s>" % (self.__class__.__name__, self.label)
return f"<{self.__class__.__name__}: {self.label}>"
Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function AppConfig.__repr__ refactored with the following changes:


@cached_property
def default_auto_field(self):
Expand All @@ -78,12 +78,7 @@ def _path_from_module(self, module):
paths = list(getattr(module, "__path__", []))
if len(paths) != 1:
filename = getattr(module, "__file__", None)
if filename is not None:
paths = [os.path.dirname(filename)]
else:
# For unknown reasons, sometimes the list returned by __path__
# contains duplicates that must be removed (#25246).
paths = list(set(paths))
paths = list(set(paths)) if filename is None else [os.path.dirname(filename)]
Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function AppConfig._path_from_module refactored with the following changes:

This removes the following comments ( why? ):

# For unknown reasons, sometimes the list returned by __path__
# contains duplicates that must be removed (#25246).

if len(paths) > 1:
raise ImproperlyConfigured(
"The app module %r has multiple filesystem locations (%r); "
Expand Down Expand Up @@ -269,9 +264,7 @@ def get_model(self, model_name, require_ready=True):
try:
return self.models[model_name.lower()]
except KeyError:
raise LookupError(
"App '%s' doesn't have a '%s' model." % (self.label, model_name)
)
raise LookupError(f"App '{self.label}' doesn't have a '{model_name}' model.")
Comment on lines -272 to +267
Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function AppConfig.get_model refactored with the following changes:


def get_models(self, include_auto_created=False, include_swapped=False):
"""
Expand Down Expand Up @@ -300,7 +293,7 @@ def import_models(self):
self.models = self.apps.all_models[self.label]

if module_has_submodule(self.module, MODELS_MODULE_NAME):
models_module_name = "%s.%s" % (self.name, MODELS_MODULE_NAME)
models_module_name = f"{self.name}.{MODELS_MODULE_NAME}"
Comment on lines -303 to +296
Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function AppConfig.import_models refactored with the following changes:

self.models_module = import_module(models_module_name)

def ready(self):
Expand Down
37 changes: 13 additions & 24 deletions unicoding_venv/lib/python3.9/site-packages/django/apps/registry.py
Original file line number Diff line number Diff line change
Expand Up @@ -85,14 +85,10 @@ def populate(self, installed_apps=None):

# Phase 1: initialize app configs and import app modules.
for entry in installed_apps:
if isinstance(entry, AppConfig):
app_config = entry
else:
app_config = AppConfig.create(entry)
app_config = entry if isinstance(entry, AppConfig) else AppConfig.create(entry)
if app_config.label in self.app_configs:
raise ImproperlyConfigured(
"Application labels aren't unique, "
"duplicates: %s" % app_config.label
f"Application labels aren't unique, duplicates: {app_config.label}"
Comment on lines -88 to +91
Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function Apps.populate refactored with the following changes:

)

self.app_configs[app_config.label] = app_config
Expand All @@ -102,11 +98,11 @@ def populate(self, installed_apps=None):
counts = Counter(
app_config.name for app_config in self.app_configs.values()
)
duplicates = [name for name, count in counts.most_common() if count > 1]
if duplicates:
if duplicates := [
name for name, count in counts.most_common() if count > 1
]:
raise ImproperlyConfigured(
"Application names aren't unique, "
"duplicates: %s" % ", ".join(duplicates)
f"""Application names aren't unique, duplicates: {", ".join(duplicates)}"""
)

self.apps_ready = True
Expand Down Expand Up @@ -157,10 +153,10 @@ def get_app_config(self, app_label):
try:
return self.app_configs[app_label]
except KeyError:
message = "No installed app with label '%s'." % app_label
message = f"No installed app with label '{app_label}'."
for app_config in self.get_app_configs():
if app_config.name == app_label:
message += " Did you mean '%s'?" % app_config.label
message += f" Did you mean '{app_config.label}'?"
Comment on lines -160 to +159
Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function Apps.get_app_config refactored with the following changes:

break
raise LookupError(message)

Expand Down Expand Up @@ -213,27 +209,21 @@ def get_model(self, app_label, model_name=None, require_ready=True):
return app_config.get_model(model_name, require_ready=require_ready)

def register_model(self, app_label, model):
# Since this method is called when models are imported, it cannot
# perform imports because of the risk of import loops. It mustn't
# call get_app_config().
model_name = model._meta.model_name
app_models = self.all_models[app_label]
model_name = model._meta.model_name
if model_name in app_models:
if (
model.__name__ == app_models[model_name].__name__
and model.__module__ == app_models[model_name].__module__
):
warnings.warn(
"Model '%s.%s' was already registered. Reloading models is not "
"advised as it can lead to inconsistencies, most notably with "
"related models." % (app_label, model_name),
f"Model '{app_label}.{model_name}' was already registered. Reloading models is not advised as it can lead to inconsistencies, most notably with related models.",
RuntimeWarning,
stacklevel=2,
)
else:
raise RuntimeError(
"Conflicting '%s' models in application '%s': %s and %s."
% (model_name, app_label, app_models[model_name], model)
f"Conflicting '{model_name}' models in application '{app_label}': {app_models[model_name]} and {model}."
Comment on lines -216 to +226
Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function Apps.register_model refactored with the following changes:

This removes the following comments ( why? ):

# Since this method is called when models are imported, it cannot
# perform imports because of the risk of import loops. It mustn't
# call get_app_config().

)
app_models[model_name] = model
self.do_pending_operations(model)
Expand Down Expand Up @@ -277,7 +267,7 @@ def get_registered_model(self, app_label, model_name):
"""
model = self.all_models[app_label].get(model_name.lower())
if model is None:
raise LookupError("Model '%s.%s' not registered." % (app_label, model_name))
raise LookupError(f"Model '{app_label}.{model_name}' not registered.")
Comment on lines -280 to +270
Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function Apps.get_registered_model refactored with the following changes:

return model

@functools.lru_cache(maxsize=None)
Expand Down Expand Up @@ -319,8 +309,7 @@ def set_available_apps(self, available):
installed = {app_config.name for app_config in self.get_app_configs()}
if not available.issubset(installed):
raise ValueError(
"Available apps isn't a subset of installed apps, extra apps: %s"
% ", ".join(available - installed)
f"""Available apps isn't a subset of installed apps, extra apps: {", ".join(available - installed)}"""
)

self.stored_app_configs.append(self.app_configs)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -41,8 +41,8 @@ class SettingsReference(str):
the value in memory but serializes to a settings.NAME attribute reference.
"""

def __new__(self, value, setting_name):
return str.__new__(self, value)
def __new__(cls, value, setting_name):
return str.__new__(cls, value)

def __init__(self, value, setting_name):
self.setting_name = setting_name
Expand All @@ -63,7 +63,7 @@ def _setup(self, name=None):
"""
settings_module = os.environ.get(ENVIRONMENT_VARIABLE)
if not settings_module:
desc = ("setting %s" % name) if name else "settings"
desc = f"setting {name}" if name else "settings"
raise ImproperlyConfigured(
"Requested %s, but settings are not configured. "
"You must either define the environment variable %s "
Expand Down Expand Up @@ -141,7 +141,7 @@ def _add_script_prefix(value):
return value
from django.urls import get_script_prefix

return "%s%s" % (get_script_prefix(), value)
return f"{get_script_prefix()}{value}"

@property
def configured(self):
Expand Down Expand Up @@ -196,9 +196,7 @@ def __init__(self, settings_module):
if setting in tuple_settings and not isinstance(
setting_value, (list, tuple)
):
raise ImproperlyConfigured(
"The %s setting must be a list or a tuple." % setting
)
raise ImproperlyConfigured(f"The {setting} setting must be a list or a tuple.")
setattr(self, setting, setting_value)
self._explicit_settings.add(setting)

Expand All @@ -219,7 +217,7 @@ def __init__(self, settings_module):
zoneinfo_root = Path("/usr/share/zoneinfo")
zone_info_file = zoneinfo_root.joinpath(*self.TIME_ZONE.split("/"))
if zoneinfo_root.exists() and not zone_info_file.exists():
raise ValueError("Incorrect timezone setting: %s" % self.TIME_ZONE)
raise ValueError(f"Incorrect timezone setting: {self.TIME_ZONE}")
# Move the time zone info into os.environ. See ticket #2315 for why
# we don't do this unconditionally (breaks Windows).
os.environ["TZ"] = self.TIME_ZONE
Expand Down
32 changes: 20 additions & 12 deletions unicoding_venv/lib/python3.9/site-packages/django/conf/urls/i18n.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,14 +10,18 @@ def i18n_patterns(*urls, prefix_default_language=True):
Add the language code prefix to every URL pattern within this function.
This may only be used in the root URLconf, not in an included URLconf.
"""
if not settings.USE_I18N:
return list(urls)
return [
URLResolver(
LocalePrefixPattern(prefix_default_language=prefix_default_language),
list(urls),
)
]
return (
[
URLResolver(
LocalePrefixPattern(
prefix_default_language=prefix_default_language
),
list(urls),
)
]
if settings.USE_I18N
else list(urls)
)


@functools.lru_cache(maxsize=None)
Expand All @@ -28,10 +32,14 @@ def is_language_prefix_patterns_used(urlconf):
`True` if the default language should be prefixed
)
"""
for url_pattern in get_resolver(urlconf).url_patterns:
if isinstance(url_pattern.pattern, LocalePrefixPattern):
return True, url_pattern.pattern.prefix_default_language
return False, False
return next(
(
(True, url_pattern.pattern.prefix_default_language)
for url_pattern in get_resolver(urlconf).url_patterns
if isinstance(url_pattern.pattern, LocalePrefixPattern)
),
(False, False),
)


urlpatterns = [
Expand Down
Loading