Skip to content

Commit

Permalink
lint and add back pyright config
Browse files Browse the repository at this point in the history
  • Loading branch information
Viicos committed Mar 6, 2024
1 parent 0b164ba commit 055c199
Show file tree
Hide file tree
Showing 7 changed files with 80 additions and 22 deletions.
50 changes: 37 additions & 13 deletions modeltranslation/admin.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,9 @@ def __init__(self, *args: Any, **kwargs: Any) -> None:
self.trans_opts = translator.get_options_for_model(self.model)
self._patch_prepopulated_fields()

def _get_declared_fieldsets(self, request: HttpRequest, obj: Any | None = None) -> _ListOrTuple[tuple[str | None, dict[str, Any]]] | None:
def _get_declared_fieldsets(
self, request: HttpRequest, obj: Any | None = None
) -> _ListOrTuple[tuple[str | None, dict[str, Any]]] | None:
# Take custom modelform fields option into account
if not self.fields and hasattr(self.form, "_meta") and self.form._meta.fields:
self.fields = self.form._meta.fields
Expand All @@ -51,12 +53,16 @@ def _get_declared_fieldsets(self, request: HttpRequest, obj: Any | None = None)
return [(None, {"fields": self.replace_orig_field(self.get_fields(request, obj))})]
return None

def formfield_for_dbfield(self, db_field: Field, request: HttpRequest, **kwargs: Any) -> forms.Field:
def formfield_for_dbfield(
self, db_field: Field, request: HttpRequest, **kwargs: Any
) -> forms.Field:
field = super().formfield_for_dbfield(db_field, request, **kwargs)
self.patch_translation_field(db_field, field, request, **kwargs) # type: ignore[arg-type]
return field # type: ignore[return-value]

def patch_translation_field(self, db_field: Field, field: forms.Field, request: HttpRequest, **kwargs: Any) -> None:
def patch_translation_field(
self, db_field: Field, field: forms.Field, request: HttpRequest, **kwargs: Any
) -> None:
if db_field.name in self.trans_opts.fields:
if field.required:
field.required = False
Expand Down Expand Up @@ -176,7 +182,9 @@ def replace_orig_field(self, option: Iterable[str | Sequence[str]]) -> _ListOrTu
option = option_new
return option # type: ignore[return-value]

def _patch_fieldsets(self, fieldsets: _ListOrTuple[tuple[str | None, dict[str, Any]]]) -> _ListOrTuple[tuple[str | None, dict[str, Any]]]:
def _patch_fieldsets(
self, fieldsets: _ListOrTuple[tuple[str | None, dict[str, Any]]]
) -> _ListOrTuple[tuple[str | None, dict[str, Any]]]:
if fieldsets:
fieldsets_new = list(fieldsets)
for name, dct in fieldsets:
Expand All @@ -186,7 +194,7 @@ def _patch_fieldsets(self, fieldsets: _ListOrTuple[tuple[str | None, dict[str, A
return fieldsets

def _patch_prepopulated_fields(self) -> None:
def localize(sources: Sequence[str], lang: str) -> tuple[str, ...]:
def localize(sources: Sequence[str], lang: str) -> tuple[str, ...]:
"Append lang suffix (if applicable) to field list"

def append_lang(source: str) -> str:
Expand All @@ -207,7 +215,9 @@ def append_lang(source: str) -> str:
prepopulated_fields[dest] = localize(sources, lang)
self.prepopulated_fields = prepopulated_fields

def _get_form_or_formset(self, request: HttpRequest, obj: Any | None, **kwargs: Any) -> dict[str, Any]:
def _get_form_or_formset(
self, request: HttpRequest, obj: Any | None, **kwargs: Any
) -> dict[str, Any]:
"""
Generic code shared by get_form and get_formset.
"""
Expand All @@ -229,14 +239,18 @@ def _get_form_or_formset(self, request: HttpRequest, obj: Any | None, **kwargs:

return kwargs

def _get_fieldsets_pre_form_or_formset(self, request: HttpRequest, obj: Any | None = None) -> _ListOrTuple[tuple[str | None, dict[str, Any]]] | None:
def _get_fieldsets_pre_form_or_formset(
self, request: HttpRequest, obj: Any | None = None
) -> _ListOrTuple[tuple[str | None, dict[str, Any]]] | None:
"""
Generic get_fieldsets code, shared by
TranslationAdmin and TranslationInlineModelAdmin.
"""
return self._get_declared_fieldsets(request, obj)

def _get_fieldsets_post_form_or_formset(self, request: HttpRequest, form: type[forms.ModelForm], obj: Any | None = None) -> list:
def _get_fieldsets_post_form_or_formset(
self, request: HttpRequest, form: type[forms.ModelForm], obj: Any | None = None
) -> list:
"""
Generic get_fieldsets code, shared by
TranslationAdmin and TranslationInlineModelAdmin.
Expand All @@ -245,7 +259,9 @@ def _get_fieldsets_post_form_or_formset(self, request: HttpRequest, form: type[f
fields = list(base_fields) + list(self.get_readonly_fields(request, obj))
return [(None, {"fields": self.replace_orig_field(fields)})]

def get_translation_field_excludes(self, exclude_languages: list[str] | None = None) -> tuple[TranslationField, ...]:
def get_translation_field_excludes(
self, exclude_languages: list[str] | None = None
) -> tuple[TranslationField, ...]:
"""
Returns a tuple of translation field names to exclude based on
`exclude_languages` arg.
Expand All @@ -263,7 +279,9 @@ def get_translation_field_excludes(self, exclude_languages: list[str] | None = N
exclude.append(tfield)
return tuple(exclude)

def get_readonly_fields(self, request: HttpRequest, obj: Any | None = None) -> _ListOrTuple[str]:
def get_readonly_fields(
self, request: HttpRequest, obj: Any | None = None
) -> _ListOrTuple[str]:
"""
Hook to specify custom readonly fields.
"""
Expand Down Expand Up @@ -355,11 +373,15 @@ def _group_fieldsets(self, fieldsets: list) -> list:

return fieldsets

def get_form(self, request: HttpRequest, obj: Any | None = None, **kwargs: Any) -> type[forms.ModelForm]:
def get_form(
self, request: HttpRequest, obj: Any | None = None, **kwargs: Any
) -> type[forms.ModelForm]:
kwargs = self._get_form_or_formset(request, obj, **kwargs)
return super().get_form(request, obj, **kwargs)

def get_fieldsets(self, request: HttpRequest, obj: Any | None = None) -> _ListOrTuple[tuple[str | None, dict[str, Any]]]:
def get_fieldsets(
self, request: HttpRequest, obj: Any | None = None
) -> _ListOrTuple[tuple[str | None, dict[str, Any]]]:
return self._get_fieldsets_pre_form_or_formset(request, obj) or self._group_fieldsets(
self._get_fieldsets_post_form_or_formset(
request, self.get_form(request, obj, fields=None), obj
Expand All @@ -368,7 +390,9 @@ def get_fieldsets(self, request: HttpRequest, obj: Any | None = None) -> _ListOr


class TranslationInlineModelAdmin(TranslationBaseModelAdmin, InlineModelAdmin):
def get_formset(self, request: HttpRequest, obj: Any | None = None, **kwargs: Any) -> type[BaseInlineFormSet]:
def get_formset(
self, request: HttpRequest, obj: Any | None = None, **kwargs: Any
) -> type[BaseInlineFormSet]:
kwargs = self._get_form_or_formset(request, obj, **kwargs)
return super().get_formset(request, obj, **kwargs)

Expand Down
3 changes: 1 addition & 2 deletions modeltranslation/management/commands/loaddata.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@

from __future__ import annotations

from typing import Any
Expand Down Expand Up @@ -41,7 +40,7 @@ def __call__(
parser: CommandParser, # type: ignore[override]
namespace: Namespace,
value: str, # type: ignore[override]
option_string: str | None = None
option_string: str | None = None,
) -> None:
check_mode(self, option_string, value, parser, namespace)

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -141,7 +141,9 @@ def get_missing_languages(self, field_name: str, db_table: str) -> Iterator[str]
if build_localized_fieldname(field_name, lang_code) not in db_table_fields:
yield lang_code

def get_sync_sql(self, field_name: str, missing_langs: list[str], model: type[Model]) -> list[str]:
def get_sync_sql(
self, field_name: str, missing_langs: list[str], model: type[Model]
) -> list[str]:
"""
Returns SQL needed for sync schema for a new translatable field.
"""
Expand Down
18 changes: 15 additions & 3 deletions modeltranslation/manager.py
Original file line number Diff line number Diff line change
Expand Up @@ -177,8 +177,10 @@ def get_field_by_colum_name(model: type[Model], col: str) -> Field:
return field
assert False, "No field found for column %s" % col


_T = TypeVar("_T", bound=Model, covariant=True)


class MultilingualQuerySet(QuerySet[_T]):
def __init__(self, *args: Any, **kwargs: Any) -> None:
super().__init__(*args, **kwargs)
Expand Down Expand Up @@ -514,6 +516,7 @@ def dates(self, field_name: str, *args: Any, **kwargs: Any) -> Self:

class FallbackValuesIterable(ValuesIterable):
queryset: MultilingualQuerySet[Model]

class X:
# This stupid class is needed as object use __slots__ and has no __dict__.
pass
Expand Down Expand Up @@ -554,13 +557,22 @@ def __iter__(self) -> Iterator[Any]:


@overload
def multilingual_queryset_factory(old_cls: type[Any], instantiate: Literal[False]) -> type[MultilingualQuerySet]: ...
def multilingual_queryset_factory(
old_cls: type[Any], instantiate: Literal[False]
) -> type[MultilingualQuerySet]:
...


@overload
def multilingual_queryset_factory(old_cls: type[Any], instantiate: Literal[True] = ...) -> MultilingualQuerySet: ...
def multilingual_queryset_factory(
old_cls: type[Any], instantiate: Literal[True] = ...
) -> MultilingualQuerySet:
...


def multilingual_queryset_factory(old_cls: type[Any], instantiate: bool = True) -> type[MultilingualQuerySet] | MultilingualQuerySet:
def multilingual_queryset_factory(
old_cls: type[Any], instantiate: bool = True
) -> type[MultilingualQuerySet] | MultilingualQuerySet:
if old_cls == models.query.QuerySet:
NewClass = MultilingualQuerySet
else:
Expand Down
13 changes: 11 additions & 2 deletions modeltranslation/translator.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,15 @@

import django
from django.core.exceptions import ImproperlyConfigured
from django.db.models import Field, ForeignKey, Manager, ManyToManyField, Model, OneToOneField, options
from django.db.models import (
Field,
ForeignKey,
Manager,
ManyToManyField,
Model,
OneToOneField,
options,
)
from django.db.models.base import ModelBase
from django.db.models.signals import post_init
from django.utils.functional import cached_property
Expand Down Expand Up @@ -585,7 +593,8 @@ def _register_single_model(self, model: type[Model], opts: TranslationOptions) -
if isinstance(field, OneToOneField):
# Fix translated_field caching for SingleRelatedObjectDescriptor
sro_descriptor = getattr(
field.remote_field.model, field.remote_field.get_accessor_name() # type: ignore[arg-type]
field.remote_field.model,
field.remote_field.get_accessor_name(), # type: ignore[arg-type]
)
patch_related_object_descriptor_caching(sro_descriptor)

Expand Down
2 changes: 1 addition & 1 deletion modeltranslation/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ def get_language() -> str:
settings.LANGUAGES (Django does not seem to guarantee this for us).
"""
lang = _get_language()
if lang is None: # Django >= 1.8
if lang is None: # Django >= 1.8
return settings.DEFAULT_LANGUAGE
if lang not in settings.AVAILABLE_LANGUAGES and "-" in lang:
lang = lang.split("-")[0]
Expand Down
12 changes: 12 additions & 0 deletions pyrightconfig.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
{
"include": ["."],
"pythonVersion": "3.7",
"pythonPlatform": "Linux",
"useLibraryCodeForTypes": true,
"strictListInference": true,
"reportMissingImports": "error",
"reportUnusedImport": "error",
"reportUnusedExpression": "error",
"reportOptionalMemberAccess": "information"
}

0 comments on commit 055c199

Please sign in to comment.