]> git.ipfire.org Git - thirdparty/babel.git/commitdiff
Use standard property annotations; get rid of :type: and :rtype: comments (#1304)
authorAarni Koskela <akx@iki.fi>
Thu, 30 Jul 2026 15:03:24 +0000 (18:03 +0300)
committerGitHub <noreply@github.com>
Thu, 30 Jul 2026 15:03:24 +0000 (18:03 +0300)
* Use property annotations instead of ... = property()

* Get rid of :type: and :rtype: comments; type annotations are more precise

babel/core.py
babel/dates.py
babel/languages.py
babel/localedata.py
babel/messages/catalog.py
babel/messages/frontend.py
babel/numbers.py
babel/plural.py

index f16bf24bf02a5f640ca2376c5a11a925f5dd85a5..eb07a8d246d3117b8be007fdd1a85b4b4bcf868d 100644 (file)
@@ -509,9 +509,9 @@ class Locale:
                 retval += f" ({detail_string})"
         return retval
 
-    display_name = property(
-        get_display_name,
-        doc="""\
+    @property
+    def display_name(self) -> str | None:
+        """
         The localized display name of the locale.
 
         >>> Locale('en').display_name
@@ -520,10 +520,8 @@ class Locale:
         'English (United States)'
         >>> Locale('sv').display_name
         'svenska'
-
-        :type: `unicode`
-        """,
-    )
+        """
+        return self.get_display_name()
 
     def get_language_name(self, locale: Locale | str | None = None) -> str | None:
         """Return the language of this locale in the given locale.
@@ -540,15 +538,15 @@ class Locale:
         locale = Locale.parse(locale)
         return locale.languages.get(self.language)
 
-    language_name = property(
-        get_language_name,
-        doc="""\
+    @property
+    def language_name(self) -> str | None:
+        """
         The localized language name of the locale.
 
         >>> Locale('en', 'US').language_name
         'English'
-    """,
-    )
+        """
+        return self.get_language_name()
 
     def get_territory_name(self, locale: Locale | str | None = None) -> str | None:
         """Return the territory name in the given locale."""
@@ -557,15 +555,15 @@ class Locale:
         locale = Locale.parse(locale)
         return locale.territories.get(self.territory or '')
 
-    territory_name = property(
-        get_territory_name,
-        doc="""\
+    @property
+    def territory_name(self) -> str | None:
+        """
         The localized territory name of the locale if available.
 
         >>> Locale('de', 'DE').territory_name
         'Deutschland'
-    """,
-    )
+        """
+        return self.get_territory_name()
 
     def get_script_name(self, locale: Locale | str | None = None) -> str | None:
         """Return the script name in the given locale."""
@@ -574,15 +572,15 @@ class Locale:
         locale = Locale.parse(locale)
         return locale.scripts.get(self.script or '')
 
-    script_name = property(
-        get_script_name,
-        doc="""\
+    @property
+    def script_name(self) -> str | None:
+        """
         The localized script name of the locale if available.
 
         >>> Locale('sr', 'ME', script='Latn').script_name
         'latinica'
-    """,
-    )
+        """
+        return self.get_script_name()
 
     @property
     def english_name(self) -> str | None:
@@ -592,8 +590,7 @@ class Locale:
         'German'
         >>> Locale('de', 'DE').english_name
         'German (Germany)'
-
-        :type: `unicode`"""
+        """
         return self.get_display_name(Locale('en'))
 
     # { General Locale Display Names
index 69610a7f01ec4e3a6dbb0573fb349c08ef675bb8..72f2c4439126ddce51170a33e110e95022ff442c 100644 (file)
@@ -146,9 +146,7 @@ def _get_datetime(instant: _Instant) -> datetime.datetime:
     True
 
     :param instant: date, time, datetime, integer, float or None
-    :type instant: date|time|datetime|int|float|None
     :return: a datetime
-    :rtype: datetime
     """
     if instant is None:
         return datetime.datetime.now(UTC).replace(tzinfo=None)
@@ -1834,8 +1832,6 @@ def tokenize_pattern(pattern: str) -> list[tuple[str, str | tuple[str, int]]]:
     For "field" tokens, the value is a tuple of (field character, repetition count).
 
     :param pattern: Pattern string
-    :type pattern: str
-    :rtype: list[tuple]
     """
     result = []
     quotebuf = None
@@ -1895,9 +1891,6 @@ def untokenize_pattern(tokens: Iterable[tuple[str, str | tuple[str, int]]]) -> s
     Turn a date format pattern token stream back into a string.
 
     This is the reverse operation of ``tokenize_pattern``.
-
-    :type tokens: Iterable[tuple]
-    :rtype: str
     """
     output = []
     for tok_type, tok_value in tokens:
@@ -1971,13 +1964,9 @@ def match_skeleton(
     'hmv'
 
     :param skeleton: The skeleton to match
-    :type skeleton: str
     :param options: An iterable of other skeletons to match against
-    :type options: Iterable[str]
     :param allow_different_fields: Whether to allow a match that uses different fields
                                    than the skeleton requested.
-    :type allow_different_fields: bool
-
     :return: The closest skeleton match, or if no match was found, None.
     :rtype: str|None
     """
index 5b2396c84c5233cf1692f842cd471c27fca65512..c4898facec9282eba672ec32ea16acd9902d614c 100644 (file)
@@ -21,13 +21,9 @@ def get_official_languages(
                  by Babel.  If you need scientifically accurate information, use another source!
 
     :param territory: Territory code
-    :type territory: str
     :param regional: Whether to return regionally official languages too
-    :type regional: bool
     :param de_facto: Whether to return de-facto official languages too
-    :type de_facto: bool
     :return: Tuple of language codes
-    :rtype: tuple[str]
     """
 
     territory = str(territory).upper()
@@ -70,9 +66,7 @@ def get_territory_language_info(
     See https://www.unicode.org/cldr/charts/latest/supplemental/territory_language_information.html
 
     :param territory: Territory code
-    :type territory: str
     :return: Language information dictionary
-    :rtype: dict[str, dict]
     """
     territory = str(territory).upper()
     return get_global("territory_languages").get(territory, {}).copy()
index 9989316d95ca87c0d852d4628e230e9ab709a3aa..297955b97454df8ca319bb482fd56f6e3aa0a665 100644 (file)
@@ -251,7 +251,6 @@ class Alias:
         that second alias will also be resolved.
 
         :param data: the locale data
-        :type data: `dict`
         """
         base = data
         for key in self.keys:
index fc345085c65f3f543ea230c9ea8bde39a33d67e1..e01fd5677b37cd6efa6e48f0621c847b479bad0b 100644 (file)
@@ -274,8 +274,7 @@ class Message:
         True
         >>> msg
         <Message 'foo' (flags: ['fuzzy'])>
-
-        :type:  `bool`"""
+        """
         return 'fuzzy' in self.flags
 
     @property
@@ -286,8 +285,7 @@ class Message:
         False
         >>> Message(('foo', 'bar')).pluralizable
         True
-
-        :type:  `bool`"""
+        """
         return isinstance(self.id, (list, tuple))
 
     @property
@@ -298,8 +296,7 @@ class Message:
         True
         >>> Message(('foo %(name)s', 'foo %(name)s')).python_format
         True
-
-        :type:  `bool`"""
+        """
         ids = self.id
         if isinstance(ids, (list, tuple)):
             for id in ids:  # Explicit loop for performance reasons.
@@ -316,8 +313,7 @@ class Message:
         True
         >>> Message(('One apple', '{count} apples')).python_brace_format
         True
-
-        :type:  `bool`"""
+        """
         ids = self.id
         if isinstance(ids, (list, tuple)):
             for id in ids:  # Explicit loop for performance reasons.
@@ -453,14 +449,17 @@ class Catalog:
             f"`locale` must be a Locale, a locale identifier string, or None; got {locale!r}",
         )
 
-    def _get_locale(self) -> Locale | None:
+    @property
+    def locale(self) -> Locale | None:
         return self._locale
 
-    def _get_locale_identifier(self) -> str | None:
-        return self._locale_identifier
+    @locale.setter
+    def locale(self, locale: Locale | str | None) -> None:
+        self._set_locale(locale)
 
-    locale = property(_get_locale, _set_locale)
-    locale_identifier = property(_get_locale_identifier)
+    @property
+    def locale_identifier(self) -> str | None:
+        return self._locale_identifier
 
     def _get_header_comment(self) -> str:
         comment = self._header_comment
@@ -481,42 +480,43 @@ class Catalog:
     def _set_header_comment(self, string: str | None) -> None:
         self._header_comment = string
 
-    header_comment = property(
-        _get_header_comment,
-        _set_header_comment,
-        doc="""\
-    The header comment for the catalog.
-
-    >>> catalog = Catalog(project='Foobar', version='1.0',
-    ...                   copyright_holder='Foo Company')
-    >>> print(catalog.header_comment) #doctest: +ELLIPSIS
-    # Translations template for Foobar.
-    # Copyright (C) ... Foo Company
-    # This file is distributed under the same license as the Foobar project.
-    # FIRST AUTHOR <EMAIL@ADDRESS>, ....
-    #
-
-    The header can also be set from a string. Any known upper-case variables
-    will be replaced when the header is retrieved again:
-
-    >>> catalog = Catalog(project='Foobar', version='1.0',
-    ...                   copyright_holder='Foo Company')
-    >>> catalog.header_comment = '''\\
-    ... # The POT for my really cool PROJECT project.
-    ... # Copyright (C) 1990-2003 ORGANIZATION
-    ... # This file is distributed under the same license as the PROJECT
-    ... # project.
-    ... #'''
-    >>> print(catalog.header_comment)
-    # The POT for my really cool Foobar project.
-    # Copyright (C) 1990-2003 Foo Company
-    # This file is distributed under the same license as the Foobar
-    # project.
-    #
-
-    :type: `unicode`
-    """,
-    )
+    @property
+    def header_comment(self) -> str:
+        """
+        The header comment for the catalog.
+
+        >>> catalog = Catalog(project='Foobar', version='1.0',
+        ...                   copyright_holder='Foo Company')
+        >>> print(catalog.header_comment) #doctest: +ELLIPSIS
+        # Translations template for Foobar.
+        # Copyright (C) ... Foo Company
+        # This file is distributed under the same license as the Foobar project.
+        # FIRST AUTHOR <EMAIL@ADDRESS>, ....
+        #
+
+        The header can also be set from a string. Any known upper-case variables
+        will be replaced when the header is retrieved again:
+
+        >>> catalog = Catalog(project='Foobar', version='1.0',
+        ...                   copyright_holder='Foo Company')
+        >>> catalog.header_comment = '''\\
+        ... # The POT for my really cool PROJECT project.
+        ... # Copyright (C) 1990-2003 ORGANIZATION
+        ... # This file is distributed under the same license as the PROJECT
+        ... # project.
+        ... #'''
+        >>> print(catalog.header_comment)
+        # The POT for my really cool Foobar project.
+        # Copyright (C) 1990-2003 Foo Company
+        # This file is distributed under the same license as the Foobar
+        # project.
+        #
+        """
+        return self._get_header_comment()
+
+    @header_comment.setter
+    def header_comment(self, value: str) -> None:
+        self._set_header_comment(value)
 
     def _get_mime_headers(self) -> list[tuple[str, str]]:
         if isinstance(self.revision_date, (datetime.datetime, datetime.time, int, float)):
@@ -588,61 +588,62 @@ class Catalog:
                 if 'YEAR' not in value:
                     self.revision_date = _parse_datetime_header(value)
 
-    mime_headers = property(
-        _get_mime_headers,
-        _set_mime_headers,
-        doc="""\
-    The MIME headers of the catalog, used for the special ``msgid ""`` entry.
-
-    The behavior of this property changes slightly depending on whether a locale
-    is set or not, the latter indicating that the catalog is actually a template
-    for actual translations.
-
-    Here's an example of the output for such a catalog template:
-
-    >>> from babel.dates import UTC
-    >>> from datetime import datetime
-    >>> created = datetime(1990, 4, 1, 15, 30, tzinfo=UTC)
-    >>> catalog = Catalog(project='Foobar', version='1.0',
-    ...                   creation_date=created)
-    >>> for name, value in catalog.mime_headers:
-    ...     print('%s: %s' % (name, value))
-    Project-Id-Version: Foobar 1.0
-    Report-Msgid-Bugs-To: EMAIL@ADDRESS
-    POT-Creation-Date: 1990-04-01 15:30+0000
-    PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE
-    Last-Translator: FULL NAME <EMAIL@ADDRESS>
-    Language-Team: LANGUAGE <LL@li.org>
-    MIME-Version: 1.0
-    Content-Type: text/plain; charset=utf-8
-    Content-Transfer-Encoding: 8bit
-    Generated-By: Babel ...
-
-    And here's an example of the output when the locale is set:
-
-    >>> revised = datetime(1990, 8, 3, 12, 0, tzinfo=UTC)
-    >>> catalog = Catalog(locale='de_DE', project='Foobar', version='1.0',
-    ...                   creation_date=created, revision_date=revised,
-    ...                   last_translator='John Doe <jd@example.com>',
-    ...                   language_team='de_DE <de@example.com>')
-    >>> for name, value in catalog.mime_headers:
-    ...     print('%s: %s' % (name, value))
-    Project-Id-Version: Foobar 1.0
-    Report-Msgid-Bugs-To: EMAIL@ADDRESS
-    POT-Creation-Date: 1990-04-01 15:30+0000
-    PO-Revision-Date: 1990-08-03 12:00+0000
-    Last-Translator: John Doe <jd@example.com>
-    Language: de_DE
-    Language-Team: de_DE <de@example.com>
-    Plural-Forms: nplurals=2; plural=(n != 1);
-    MIME-Version: 1.0
-    Content-Type: text/plain; charset=utf-8
-    Content-Transfer-Encoding: 8bit
-    Generated-By: Babel ...
-
-    :type: `list`
-    """,
-    )
+    @property
+    def mime_headers(self) -> list[tuple[str, str]]:
+        """
+        The MIME headers of the catalog, used for the special ``msgid ""`` entry.
+
+        The behavior of this property changes slightly depending on whether a locale
+        is set or not, the latter indicating that the catalog is actually a template
+        for actual translations.
+
+        Here's an example of the output for such a catalog template:
+
+        >>> from babel.dates import UTC
+        >>> from datetime import datetime
+        >>> created = datetime(1990, 4, 1, 15, 30, tzinfo=UTC)
+        >>> catalog = Catalog(project='Foobar', version='1.0',
+        ...                   creation_date=created)
+        >>> for name, value in catalog.mime_headers:
+        ...     print('%s: %s' % (name, value))
+        Project-Id-Version: Foobar 1.0
+        Report-Msgid-Bugs-To: EMAIL@ADDRESS
+        POT-Creation-Date: 1990-04-01 15:30+0000
+        PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE
+        Last-Translator: FULL NAME <EMAIL@ADDRESS>
+        Language-Team: LANGUAGE <LL@li.org>
+        MIME-Version: 1.0
+        Content-Type: text/plain; charset=utf-8
+        Content-Transfer-Encoding: 8bit
+        Generated-By: Babel ...
+
+        And here's an example of the output when the locale is set:
+
+        >>> revised = datetime(1990, 8, 3, 12, 0, tzinfo=UTC)
+        >>> catalog = Catalog(locale='de_DE', project='Foobar', version='1.0',
+        ...                   creation_date=created, revision_date=revised,
+        ...                   last_translator='John Doe <jd@example.com>',
+        ...                   language_team='de_DE <de@example.com>')
+        >>> for name, value in catalog.mime_headers:
+        ...     print('%s: %s' % (name, value))
+        Project-Id-Version: Foobar 1.0
+        Report-Msgid-Bugs-To: EMAIL@ADDRESS
+        POT-Creation-Date: 1990-04-01 15:30+0000
+        PO-Revision-Date: 1990-08-03 12:00+0000
+        Last-Translator: John Doe <jd@example.com>
+        Language: de_DE
+        Language-Team: de_DE <de@example.com>
+        Plural-Forms: nplurals=2; plural=(n != 1);
+        MIME-Version: 1.0
+        Content-Type: text/plain; charset=utf-8
+        Content-Transfer-Encoding: 8bit
+        Generated-By: Babel ...
+        """
+        return self._get_mime_headers()
+
+    @mime_headers.setter
+    def mime_headers(self, value: Iterable[tuple[str, str]]) -> None:
+        self._set_mime_headers(value)
 
     @property
     def num_plurals(self) -> int:
@@ -652,8 +653,7 @@ class Catalog:
         2
         >>> Catalog(locale='ga').num_plurals
         5
-
-        :type: `int`"""
+        """
         if self._num_plurals is None:
             num = 2
             if self.locale:
@@ -671,8 +671,7 @@ class Catalog:
         '(n == 1 ? 0 : n == 2 ? 1 : n >= 3 && n <= 6 ? 2 : n >= 7 && n <= 10 ? 3 : 4)'
         >>> Catalog(locale='ding').plural_expr  # unknown locale
         '(n != 1)'
-
-        :type: `str`"""
+        """
         if self._plural_expr is None:
             expr = '(n != 1)'
             if self.locale:
@@ -688,8 +687,7 @@ class Catalog:
         'nplurals=2; plural=(n != 1);'
         >>> Catalog(locale='pt_BR').plural_forms
         'nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % 1000000 == 0 ? 1 : 2;'
-
-        :type: `str`"""
+        """
         return f"nplurals={self.num_plurals}; plural={self.plural_expr};"
 
     def __contains__(self, id: _MessageID) -> bool:
index f63dd9dedb09ce393ad9c3bd8a1a5955444f7eff..1df1e225f7c5dde555dd5bd79c62ee80e2738bc8 100644 (file)
@@ -997,11 +997,7 @@ class CommandLineInterface:
         for name, description in sorted(self.commands.items()):
             print(f"  {name:<{cmd_width}} {description}")
 
-    def _configure_command(self, cmdname, argv):
-        """
-        :type cmdname: str
-        :type argv: list[str]
-        """
+    def _configure_command(self, cmdname: str, argv: list[str]) -> CommandMixin:
         cmdclass = self.command_classes[cmdname]
         cmdinst = cmdclass()
         if self.log:
index 2ef9031aae3c4de95736d533186458c5d654a1d8..767bac95ac6b8f458a6ae83ca7c3946a32178b38 100644 (file)
@@ -1243,11 +1243,8 @@ def _remove_trailing_zeros_after_decimal(string: str, decimal_symbol: str) -> st
     is also removed. If the string does not contain the decimal symbol, it is returned unchanged.
 
     :param string: The numeric string from which to remove trailing zeros.
-    :type string: str
     :param decimal_symbol: The symbol used to denote the decimal point.
-    :type decimal_symbol: str
     :return: The numeric string with trailing zeros removed from its decimal part.
-    :rtype: str
 
     Example:
     >>> _remove_trailing_zeros_after_decimal("123.4500", ".")
@@ -1462,19 +1459,14 @@ class NumberPattern:
 
         :param value: The value to format. If this is not a Decimal object,
                       it will be cast to one.
-        :type value: decimal.Decimal|float|int
         :param locale: The locale to use for formatting.
-        :type locale: str|babel.core.Locale
         :param currency: Which currency, if any, to format as.
-        :type currency: str|None
         :param currency_digits: Whether or not to use the currency's precision.
                                 If false, the pattern's precision is used.
-        :type currency_digits: bool
         :param decimal_quantization: Whether decimal numbers should be forcibly
                                      quantized to produce a formatted output
                                      strictly matching the CLDR definition for
                                      the locale.
-        :type decimal_quantization: bool
         :param force_frac: DEPRECATED - a forced override for `self.frac_prec`
                            for a single formatting invocation.
         :param group_separator: Whether to use the locale's number group separator.
index 90aa4952d13db3e5bf601ea687f4c58b042877f6..14cadceff09dc5e0fa9ca1bd7b62aeec88178eaf 100644 (file)
@@ -42,7 +42,6 @@ def extract_operands(
     .. _`CLDR rules`: https://www.unicode.org/reports/tr35/tr35-61/tr35-numbers.html#Operands
 
     :param source: A real number
-    :type source: int|float|decimal.Decimal
     :return: A n-i-v-w-f-t-c-e tuple
     :rtype: tuple[decimal.Decimal, int, int, int, int, int, int, int]
     """