Skip to content

Commit

Permalink
chore: annotate or fix private variables usage
Browse files Browse the repository at this point in the history
  • Loading branch information
nijel committed Jul 12, 2024
1 parent 1e144df commit 152c117
Show file tree
Hide file tree
Showing 20 changed files with 45 additions and 42 deletions.
3 changes: 1 addition & 2 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -360,8 +360,7 @@ ignore = [
"PLW2901", # TODO: overwriting variables inside loop
"PLW1514", # TODO: `open` in text mode without explicit `encoding` argument
"FURB101", # TODO: `open` and `read` should be replaced by `Path(hostsfile).read_text()`
"FURB103", # TODO: `open` and `write` should be replaced by `Path(name).write_text(content)`
"SLF001" # TODO: Private member accessed (might need noqa tags)
"FURB103" # TODO: `open` and `write` should be replaced by `Path(name).write_text(content)`
]
preview = true
select = ["ALL"]
Expand Down
6 changes: 3 additions & 3 deletions weblate/accounts/middleware.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,16 +22,16 @@ def get_user(request):
Adds handling of anonymous user which is stored in database.
"""
if not hasattr(request, "_cached_user"):
if not hasattr(request, "weblate_cached_user"):
user = auth.get_user(request)
if isinstance(user, AnonymousUser):
user = get_anonymous()
# Make sure user permissions are fetched again, needed as
# get_anonymous() is reusing same instance.
user.clear_cache()

request._cached_user = user
return request._cached_user
request.weblate_cached_user = user
return request.weblate_cached_user


class AuthenticationMiddleware:
Expand Down
2 changes: 1 addition & 1 deletion weblate/accounts/strategy.py
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ def request_data(self, merge=True):

def build_absolute_uri(self, path=None):
if self.request:
self.request.__dict__["_current_scheme_host"] = get_site_url()
self.request._current_scheme_host = get_site_url() # noqa: SLF001
return super().build_absolute_uri(path)

def clean_partial_pipeline(self, token) -> None:
Expand Down
2 changes: 1 addition & 1 deletion weblate/auth/tests/test_models.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ def setUp(self) -> None:

def test_num_queries(self) -> None:
with self.assertNumQueries(8):
self.user._fetch_permissions()
self.user._fetch_permissions() # noqa: SLF001

def test_project(self) -> None:
# No permissions
Expand Down
2 changes: 1 addition & 1 deletion weblate/checks/flags.py
Original file line number Diff line number Diff line change
Expand Up @@ -191,7 +191,7 @@ def get_items(
return ()
if isinstance(flags, str):
return parse_flags_text(flags)
if isinstance(flags, etree._Element):
if isinstance(flags, etree._Element): # noqa: SLF001
return tuple(parse_flags_xml(flags))
if isinstance(flags, Flags):
return flags.items()
Expand Down
6 changes: 3 additions & 3 deletions weblate/configuration/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,8 +24,8 @@ class CustomCSSView(TemplateView):
@classmethod
def get_css(cls, request):
# Request level caching
if hasattr(request, "_weblate_custom_css"):
return request._weblate_custom_css
if hasattr(request, "weblate_custom_css"):
return request.weblate_custom_css

# Site level caching
css = cache.get(cls.cache_key)
Expand All @@ -35,7 +35,7 @@ def get_css(cls, request):
Setting.objects.get_settings_dict(Setting.CATEGORY_UI),
).strip()
cache.set(cls.cache_key, css, 24 * 3600)
request._weblate_custom_css = css
request.weblate_custom_css = css
return css

def get(self, request, *args, **kwargs):
Expand Down
2 changes: 1 addition & 1 deletion weblate/formats/exporters.py
Original file line number Diff line number Diff line change
Expand Up @@ -289,7 +289,7 @@ class AndroidResourceExporter(XMLFilterMixin, MonolingualExporter):

def add(self, unit, word) -> None:
# Need to have storage to handle plurals
unit._store = self.storage
unit._store = self.storage # noqa: SLF001
super().add(unit, word)

def add_note(self, output, note: str, origin: str) -> None:
Expand Down
2 changes: 1 addition & 1 deletion weblate/formats/ttkit.py
Original file line number Diff line number Diff line change
Expand Up @@ -359,7 +359,7 @@ def construct_unit(self, source: str):
else:
unit = self.store.UnitClass(source)
# Needed by some formats (Android) to set target
unit._store = self.store
unit._store = self.store # noqa: SLF001
return unit

def create_unit_key(
Expand Down
23 changes: 12 additions & 11 deletions weblate/lang/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -671,7 +671,8 @@ def uses_whitespace(self) -> bool:

@cached_property
def plural(self):
if self.plural_set.all()._result_cache is not None:
# Filter in Python if query is cached
if self.plural_set.all()._result_cache is not None: # noqa: SLF001
for plural in self.plural_set.all():
if plural.source == Plural.SOURCE_DEFAULT:
return plural
Expand Down Expand Up @@ -956,7 +957,7 @@ def __init__(self, source_plural, target_plural) -> None:
self.same_plurals = source_plural.same_as(target_plural)

@cached_property
def _target_map(self):
def target_map(self):
exact_source_map = {}
all_source_map = {}
for i, examples in self.source_plural.examples.items():
Expand All @@ -967,23 +968,23 @@ def _target_map(self):
all_source_map[example] = i

target_plural = self.target_plural
target_map = []
result = []
last = target_plural.number - 1
for i in range(target_plural.number):
examples = target_plural.examples.get(i, ())
if len(examples) == 1:
number = examples[0]
if number in exact_source_map:
target_map.append((exact_source_map[number], None))
result.append((exact_source_map[number], None))
elif number in all_source_map:
target_map.append((all_source_map[number], number))
result.append((all_source_map[number], number))
else:
target_map.append((-1, number))
result.append((-1, number))
elif i == last:
target_map.append((-1, None))
result.append((-1, None))
else:
target_map.append((None, None))
return tuple(target_map)
result.append((None, None))
return tuple(result)

def map(self, unit):
source_strings = unit.get_source_plurals()
Expand All @@ -1005,7 +1006,7 @@ def map(self, unit):
),
None,
)
for source_index, number_to_interpolate in self._target_map:
for source_index, number_to_interpolate in self.target_map:
s = "" if source_index is None else source_strings[source_index]
if s and number_to_interpolate is not None and format_check:
s = format_check.interpolate_number(s, number_to_interpolate)
Expand All @@ -1029,7 +1030,7 @@ def zip(self, sources, targets, unit):
return zip(sources, targets, strict=True)
return [
(sources[-1 if i is None else i], targets[j])
for (i, _), j in zip(self._target_map, range(len(targets)), strict=True)
for (i, _), j in zip(self.target_map, range(len(targets)), strict=True)
]


Expand Down
10 changes: 5 additions & 5 deletions weblate/lang/tests.py
Original file line number Diff line number Diff line change
Expand Up @@ -685,7 +685,7 @@ def test_english_czech(self) -> None:
english = Language.objects.get(code="en")
czech = Language.objects.get(code="cs")
mapper = PluralMapper(english.plural, czech.plural)
self.assertEqual(mapper._target_map, ((0, None), (None, None), (-1, None)))
self.assertEqual(mapper.target_map, ((0, None), (None, None), (-1, None)))
unit = Unit.objects.get(
translation__language=english, id_hash=2097404709965985808
)
Expand All @@ -698,7 +698,7 @@ def test_russian_english(self) -> None:
russian = Language.objects.get(code="ru")
english = Language.objects.get(code="en")
mapper = PluralMapper(russian.plural, english.plural)
self.assertEqual(mapper._target_map, ((0, "1"), (-1, None)))
self.assertEqual(mapper.target_map, ((0, "1"), (-1, None)))
# Use English here to test incomplete plural set in the source string
unit = Unit.objects.get(
translation__language=english, id_hash=2097404709965985808
Expand All @@ -712,7 +712,7 @@ def test_russian_english_interpolate(self) -> None:
russian = Language.objects.get(code="ru")
english = Language.objects.get(code="en")
mapper = PluralMapper(russian.plural, english.plural)
self.assertEqual(mapper._target_map, ((0, "1"), (-1, None)))
self.assertEqual(mapper.target_map, ((0, "1"), (-1, None)))
# Use English here to test incomplete plural set in the source string
unit = Unit.objects.get(
translation__language=english, id_hash=2097404709965985808
Expand All @@ -728,7 +728,7 @@ def test_russian_english_interpolate_double(self) -> None:
russian = Language.objects.get(code="ru")
english = Language.objects.get(code="en")
mapper = PluralMapper(russian.plural, english.plural)
self.assertEqual(mapper._target_map, ((0, "1"), (-1, None)))
self.assertEqual(mapper.target_map, ((0, "1"), (-1, None)))
# Use English here to test incomplete plural set in the source string
unit = Unit.objects.get(
translation__language=english, id_hash=2097404709965985808
Expand All @@ -747,7 +747,7 @@ def test_russian_english_interpolate_missing(self) -> None:
russian = Language.objects.get(code="ru")
english = Language.objects.get(code="en")
mapper = PluralMapper(russian.plural, english.plural)
self.assertEqual(mapper._target_map, ((0, "1"), (-1, None)))
self.assertEqual(mapper.target_map, ((0, "1"), (-1, None)))
unit = Unit.objects.get(
translation__language=english, id_hash=2097404709965985808
)
Expand Down
2 changes: 1 addition & 1 deletion weblate/middleware.py
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ def __init__(self, get_response=None) -> None:
def __call__(self, request):
# Fake HttpRequest attribute to inject configured
# site name into build_absolute_uri
request._current_scheme_host = get_site_url()
request._current_scheme_host = get_site_url() # noqa: SLF001

# Actual proxy handling
proxy = None
Expand Down
2 changes: 1 addition & 1 deletion weblate/trans/management/commands/import_json.py
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,7 @@ def handle(self, *args, **options) -> None: # noqa: C901

allfields = {
field.name
for field in Component._meta.get_fields()
for field in Component._meta.get_fields() # noqa: SLF001
if field.editable and not field.is_relation
}

Expand Down
5 changes: 4 additions & 1 deletion weblate/trans/models/category.py
Original file line number Diff line number Diff line change
Expand Up @@ -127,7 +127,10 @@ def get_url_path(self):

def _get_childs_depth(self):
return 1 + max(
(child._get_childs_depth() for child in self.category_set.all()),
(
child._get_childs_depth() # noqa: SLF001
for child in self.category_set.all()
),
default=0,
)

Expand Down
2 changes: 1 addition & 1 deletion weblate/trans/models/component.py
Original file line number Diff line number Diff line change
Expand Up @@ -2013,7 +2013,7 @@ def reuse_self(translation):

components[component.pk] = component
with self.start_sentry_span("commit_pending"):
translation._commit_pending(reason, user)
translation._commit_pending(reason, user) # noqa: SLF001
if component.has_template():
translation_pks[component.pk].append(translation.pk)
if translation.is_source:
Expand Down
4 changes: 2 additions & 2 deletions weblate/trans/models/translation.py
Original file line number Diff line number Diff line change
Expand Up @@ -306,7 +306,7 @@ def sync_unit(
# Avoid fetching empty list of checks from the database
newunit.all_checks = []
# Avoid fetching empty list of variants
newunit._prefetched_objects_cache = {
newunit._prefetched_objects_cache = { # noqa: SLF001
"defined_variants": Variant.objects.none()
}
is_new = True
Expand Down Expand Up @@ -1512,7 +1512,7 @@ def add_unit( # noqa: C901
# The source language is always first in the translations array
if source_unit is None:
source_unit = unit
component._sources[id_hash] = unit
component._sources[id_hash] = unit # noqa: SLF001
if translation == self:
result = unit
unit_ids.append(unit.pk)
Expand Down
2 changes: 1 addition & 1 deletion weblate/trans/tests/test_views.py
Original file line number Diff line number Diff line change
Expand Up @@ -144,7 +144,7 @@ def get_request(self, user=None):
request.user = user or self.user
request.session = "session"
messages = FallbackStorage(request)
request._messages = messages
request._messages = messages # noqa: SLF001
return request

def get_translation(self, language="cs"):
Expand Down
2 changes: 1 addition & 1 deletion weblate/utils/markdown.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ def get_mention_users(text):
class SkipHtmlSpan(span_token.HtmlSpan):
"""A token that strips HTML tags from the content."""

pattern = re.compile(f"{span_token._open_tag}|{span_token._closing_tag}")
pattern = re.compile(f"{span_token._open_tag}|{span_token._closing_tag}") # noqa: SLF001
parse_inner = False
content: str

Expand Down
2 changes: 1 addition & 1 deletion weblate/utils/stats.py
Original file line number Diff line number Diff line change
Expand Up @@ -849,7 +849,7 @@ def _calculate_basic(self) -> None:

# Ensure all objects have data available so that we can use _dict directly
for stats_obj in all_stats:
if "all" not in stats_obj._data:
if "all" not in stats_obj._data: # noqa: SLF001
stats_obj.calculate_basic()
stats_obj.save()

Expand Down
2 changes: 1 addition & 1 deletion weblate/utils/tests/test_ratelimit.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ def get_request(self):
request.META["REMOTE_ADDR"] = "1.2.3.4"
request.method = "POST"
request.session = SessionStore()
request._messages = default_storage(request)
request._messages = default_storage(request) # noqa: SLF001
request.user = AnonymousUser()
return request

Expand Down
6 changes: 3 additions & 3 deletions weblate/wladmin/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -318,8 +318,8 @@ def __str__(self) -> str:


def get_support_status(request: HttpRequest) -> SupportStatus:
if hasattr(request, "_weblate_support_status"):
support_status = request._weblate_support_status
if hasattr(request, "weblate_support_status"):
support_status = request.weblate_support_status
else:
support_status = cache.get(SUPPORT_STATUS_CACHE_KEY)
if support_status is None:
Expand All @@ -329,5 +329,5 @@ def get_support_status(request: HttpRequest) -> SupportStatus:
"in_limits": support_status_instance.in_limits,
}
cache.set(SUPPORT_STATUS_CACHE_KEY, support_status, 86400)
request._weblate_support_status = support_status
request.weblate_support_status = support_status
return support_status

0 comments on commit 152c117

Please sign in to comment.