aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorrobot-contrib <robot-contrib@yandex-team.com>2023-11-08 08:02:42 +0300
committerrobot-contrib <robot-contrib@yandex-team.com>2023-11-08 08:31:37 +0300
commitfd01b46f68dae86217fed11f93dbdce52d09fae5 (patch)
treec5c6b0d8e04a284b719fd6ef186973a922f6529a
parentc29324adfbbd2c4bafa31109bc5890e9771fd541 (diff)
downloadydb-fd01b46f68dae86217fed11f93dbdce52d09fae5.tar.gz
Update contrib/python/traitlets/py3 to 5.12.0
-rw-r--r--contrib/python/traitlets/py3/.dist-info/METADATA11
-rw-r--r--contrib/python/traitlets/py3/tests/_warnings.py4
-rw-r--r--contrib/python/traitlets/py3/tests/config/test_application.py9
-rw-r--r--contrib/python/traitlets/py3/tests/config/test_loader.py8
-rw-r--r--contrib/python/traitlets/py3/tests/test_traitlets.py12
-rw-r--r--contrib/python/traitlets/py3/traitlets/_version.py2
-rw-r--r--contrib/python/traitlets/py3/traitlets/config/application.py32
-rw-r--r--contrib/python/traitlets/py3/traitlets/config/argcomplete_config.py22
-rw-r--r--contrib/python/traitlets/py3/traitlets/config/configurable.py20
-rw-r--r--contrib/python/traitlets/py3/traitlets/config/loader.py10
-rw-r--r--contrib/python/traitlets/py3/traitlets/traitlets.py117
-rw-r--r--contrib/python/traitlets/py3/traitlets/utils/__init__.py2
-rw-r--r--contrib/python/traitlets/py3/traitlets/utils/decorators.py4
-rw-r--r--contrib/python/traitlets/py3/traitlets/utils/descriptions.py6
-rw-r--r--contrib/python/traitlets/py3/ya.make2
15 files changed, 138 insertions, 123 deletions
diff --git a/contrib/python/traitlets/py3/.dist-info/METADATA b/contrib/python/traitlets/py3/.dist-info/METADATA
index fb63430a4c..8d2ecd4ba3 100644
--- a/contrib/python/traitlets/py3/.dist-info/METADATA
+++ b/contrib/python/traitlets/py3/.dist-info/METADATA
@@ -1,8 +1,12 @@
Metadata-Version: 2.1
Name: traitlets
-Version: 5.11.2
+Version: 5.12.0
Summary: Traitlets Python configuration system
Project-URL: Homepage, https://github.com/ipython/traitlets
+Project-URL: Documentation, https://traitlets.readthedocs.io
+Project-URL: Source, https://github.com/ipython/traitlets
+Project-URL: Funding, https://numfocus.org
+Project-URL: Tracker, https://github.com/ipython/traitlets/issues
Author-email: IPython Development Team <ipython-dev@python.org>
License: BSD 3-Clause License
@@ -36,12 +40,15 @@ License: BSD 3-Clause License
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
License-File: LICENSE
Keywords: Interactive,Interpreter,Shell,Web
+Classifier: Framework :: IPython
+Classifier: Framework :: Jupyter
Classifier: Intended Audience :: Developers
Classifier: Intended Audience :: Science/Research
Classifier: Intended Audience :: System Administrators
Classifier: License :: OSI Approved :: BSD License
Classifier: Programming Language :: Python
Classifier: Programming Language :: Python :: 3
+Classifier: Typing :: Typed
Requires-Python: >=3.8
Provides-Extra: docs
Requires-Dist: myst-parser; extra == 'docs'
@@ -49,7 +56,7 @@ Requires-Dist: pydata-sphinx-theme; extra == 'docs'
Requires-Dist: sphinx; extra == 'docs'
Provides-Extra: test
Requires-Dist: argcomplete>=3.0.3; extra == 'test'
-Requires-Dist: mypy>=1.5.1; extra == 'test'
+Requires-Dist: mypy>=1.6.0; extra == 'test'
Requires-Dist: pre-commit; extra == 'test'
Requires-Dist: pytest-mock; extra == 'test'
Requires-Dist: pytest-mypy-testing; extra == 'test'
diff --git a/contrib/python/traitlets/py3/tests/_warnings.py b/contrib/python/traitlets/py3/tests/_warnings.py
index e3c3a0ac6d..1fb6e9a9a5 100644
--- a/contrib/python/traitlets/py3/tests/_warnings.py
+++ b/contrib/python/traitlets/py3/tests/_warnings.py
@@ -38,7 +38,7 @@ def all_warnings():
"""
# Whenever a warning is triggered, Python adds a __warningregistry__
- # member to the *calling* module. The exercize here is to find
+ # member to the *calling* module. The exercise here is to find
# and eradicate all those breadcrumbs that were left lying around.
#
# We proceed by first searching all parent calling frames and explicitly
@@ -88,7 +88,7 @@ def expected_warnings(matching):
Raises a ValueError if any match was not found or an unexpected
warning was raised.
Allows for three types of behaviors: "and", "or", and "optional" matches.
- This is done to accomodate different build enviroments or loop conditions
+ This is done to accommodate different build environments or loop conditions
that may produce different warnings. The behaviors can be combined.
If you pass multiple patterns, you get an orderless "and", where all of the
warnings must be raised.
diff --git a/contrib/python/traitlets/py3/tests/config/test_application.py b/contrib/python/traitlets/py3/tests/config/test_application.py
index 610cafc3cd..94427d6b38 100644
--- a/contrib/python/traitlets/py3/tests/config/test_application.py
+++ b/contrib/python/traitlets/py3/tests/config/test_application.py
@@ -14,7 +14,7 @@ import sys
import typing as t
from io import StringIO
from tempfile import TemporaryDirectory
-from unittest import TestCase
+from unittest import TestCase, mock
import pytest
from pytest import mark
@@ -25,11 +25,6 @@ from traitlets.config.configurable import Configurable
from traitlets.config.loader import Config, KVArgParseConfigLoader
from traitlets.tests.utils import check_help_all_output, check_help_output, get_output_error_code
-try:
- from unittest import mock
-except ImportError:
- from unittest import mock
-
pjoin = os.path.join
@@ -665,7 +660,7 @@ class TestApplication(TestCase):
with self.assertRaises(AttributeError):
app.loaded_config_files = "/foo" # type:ignore
- # ensure it can't be udpated via append
+ # ensure it can't be updated via append
app.loaded_config_files.append("/bar")
self.assertEqual(len(app.loaded_config_files), 1)
diff --git a/contrib/python/traitlets/py3/tests/config/test_loader.py b/contrib/python/traitlets/py3/tests/config/test_loader.py
index 3a1f96120f..9d864317bc 100644
--- a/contrib/python/traitlets/py3/tests/config/test_loader.py
+++ b/contrib/python/traitlets/py3/tests/config/test_loader.py
@@ -629,7 +629,7 @@ class TestConfig(TestCase):
"""
With multiple config files (systemwide and users), we want compounding.
- If systemwide overwirte and user append, we want both in the right
+ If systemwide overwrite and user append, we want both in the right
order.
"""
c1 = Config()
@@ -702,7 +702,7 @@ class TestConfig(TestCase):
"""
With multiple config files (systemwide and users), we want compounding.
- dict update shoudl be in the right order.
+ dict update should be in the right order.
"""
c1 = Config()
c2 = Config()
@@ -720,7 +720,7 @@ class TestConfig(TestCase):
"""
With multiple config files (systemwide and users), we want compounding.
- Later dict overwrite lazyness
+ Later dict overwrite laziness
"""
c1 = Config()
c2 = Config()
@@ -738,7 +738,7 @@ class TestConfig(TestCase):
"""
With multiple config files (systemwide and users), we want compounding.
- Later dict overwrite lazyness
+ Later dict overwrite laziness
"""
c1 = Config()
c2 = Config()
diff --git a/contrib/python/traitlets/py3/tests/test_traitlets.py b/contrib/python/traitlets/py3/tests/test_traitlets.py
index 62fa726f19..07c95ca251 100644
--- a/contrib/python/traitlets/py3/tests/test_traitlets.py
+++ b/contrib/python/traitlets/py3/tests/test_traitlets.py
@@ -2013,7 +2013,7 @@ class TestLink(TestCase):
a = A(value=9)
b = A(value=8)
- # Conenct the two classes.
+ # Connect the two classes.
c = link((a, "value"), (b, "value"))
# Make sure the values are the same at the point of linking.
@@ -2038,7 +2038,7 @@ class TestLink(TestCase):
a = A(value=9)
b = B(count=8)
- # Conenct the two classes.
+ # Connect the two classes.
c = link((a, "value"), (b, "count"))
# Make sure the values are the same at the point of linking.
@@ -2126,7 +2126,7 @@ class TestLink(TestCase):
a = A(value=9)
b = A(value=8)
- # Conenct the two classes.
+ # Connect the two classes.
c = link((a, "value"), (b, "value"), transform=(lambda x: 2 * x, lambda x: int(x / 2.0)))
# Make sure the values are correct at the point of linking.
@@ -2178,7 +2178,7 @@ class TestDirectionalLink(TestCase):
a = A(value=9)
b = A(value=8)
- # Conenct the two classes.
+ # Connect the two classes.
c = directional_link((a, "value"), (b, "value"))
# Make sure the values are the same at the point of linking.
@@ -2201,7 +2201,7 @@ class TestDirectionalLink(TestCase):
a = A(value=9)
b = A(value=8)
- # Conenct the two classes.
+ # Connect the two classes.
c = directional_link((a, "value"), (b, "value"), lambda x: 2 * x)
# Make sure the values are correct at the point of linking.
@@ -2227,7 +2227,7 @@ class TestDirectionalLink(TestCase):
a = A(value=9)
b = B(count=8)
- # Conenct the two classes.
+ # Connect the two classes.
c = directional_link((a, "value"), (b, "count"))
# Make sure the values are the same at the point of linking.
diff --git a/contrib/python/traitlets/py3/traitlets/_version.py b/contrib/python/traitlets/py3/traitlets/_version.py
index 5fbb9a2599..aed118ffe6 100644
--- a/contrib/python/traitlets/py3/traitlets/_version.py
+++ b/contrib/python/traitlets/py3/traitlets/_version.py
@@ -5,7 +5,7 @@ import re
from typing import List
# Version string must appear intact for hatch versioning
-__version__ = "5.11.2"
+__version__ = "5.12.0"
# Build up version_info tuple for backwards compatibility
pattern = r"(?P<major>\d+).(?P<minor>\d+).(?P<patch>\d+)(?P<rest>.*)"
diff --git a/contrib/python/traitlets/py3/traitlets/config/application.py b/contrib/python/traitlets/py3/traitlets/config/application.py
index 5993b4c7f2..bf7308dc5e 100644
--- a/contrib/python/traitlets/py3/traitlets/config/application.py
+++ b/contrib/python/traitlets/py3/traitlets/config/application.py
@@ -298,7 +298,7 @@ class Application(SingletonConfigurable):
log = logging.getLogger(self.__class__.__name__)
log.propagate = False
_log = log # copied from Logger.hasHandlers() (new in Python 3.2)
- while _log:
+ while _log is not None:
if _log.handlers:
return log
if not _log.propagate:
@@ -337,21 +337,21 @@ class Application(SingletonConfigurable):
.. code-block:: python
c.Application.logging_config = {
- 'handlers': {
- 'file': {
- 'class': 'logging.FileHandler',
- 'level': 'DEBUG',
- 'filename': '<path/to/file>',
+ "handlers": {
+ "file": {
+ "class": "logging.FileHandler",
+ "level": "DEBUG",
+ "filename": "<path/to/file>",
}
},
- 'loggers': {
- '<application-name>': {
- 'level': 'DEBUG',
+ "loggers": {
+ "<application-name>": {
+ "level": "DEBUG",
# NOTE: if you don't list the default "console"
# handler here then it will be disabled
- 'handlers': ['console', 'file'],
+ "handlers": ["console", "file"],
},
- }
+ },
}
""",
@@ -535,7 +535,7 @@ class Application(SingletonConfigurable):
trait = cls.class_traits(config=True)[traitname]
fhelp_lines = cls.class_get_trait_help(trait, helptext=fhelp).splitlines()
- if not isinstance(alias, tuple):
+ if not isinstance(alias, tuple): # type:ignore[unreachable]
alias = (alias,) # type:ignore[assignment]
alias = sorted(alias, key=len) # type:ignore[assignment]
alias = ", ".join(("--%s" if len(m) > 1 else "-%s") % m for m in alias)
@@ -559,7 +559,7 @@ class Application(SingletonConfigurable):
for flags, (cfg, fhelp) in self.flags.items():
try:
- if not isinstance(flags, tuple):
+ if not isinstance(flags, tuple): # type:ignore[unreachable]
flags = (flags,) # type:ignore[assignment]
flags = sorted(flags, key=len) # type:ignore[assignment]
flags = ", ".join(("--%s" if len(m) > 1 else "-%s") % m for m in flags)
@@ -643,7 +643,7 @@ class Application(SingletonConfigurable):
if classes:
help_classes = self._classes_with_config_traits()
- if help_classes:
+ if help_classes is not None:
yield "Class options"
yield "============="
for p in wrap_paragraphs(self.keyvalue_description):
@@ -752,7 +752,7 @@ class Application(SingletonConfigurable):
if len(children) == 1:
# exactly one descendent, promote alias
cls = children[0] # type:ignore[assignment]
- if not isinstance(aliases, tuple):
+ if not isinstance(aliases, tuple): # type:ignore[unreachable]
alias = (alias,) # type:ignore[assignment]
for al in alias:
aliases[al] = ".".join([cls, trait]) # type:ignore[list-item]
@@ -773,7 +773,7 @@ class Application(SingletonConfigurable):
else:
newflag[cls] = subdict
- if not isinstance(key, tuple):
+ if not isinstance(key, tuple): # type:ignore[unreachable]
key = (key,) # type:ignore[assignment]
for k in key:
flags[k] = (newflag, help)
diff --git a/contrib/python/traitlets/py3/traitlets/config/argcomplete_config.py b/contrib/python/traitlets/py3/traitlets/config/argcomplete_config.py
index 82112aaf6b..9588b88985 100644
--- a/contrib/python/traitlets/py3/traitlets/config/argcomplete_config.py
+++ b/contrib/python/traitlets/py3/traitlets/config/argcomplete_config.py
@@ -10,7 +10,7 @@ import typing as t
try:
import argcomplete
- from argcomplete import CompletionFinder # type:ignore
+ from argcomplete import CompletionFinder
except ImportError:
# This module and its utility methods are written to not crash even
# if argcomplete is not installed.
@@ -20,8 +20,8 @@ except ImportError:
raise ModuleNotFoundError("No module named 'argcomplete'")
raise AttributeError(f"argcomplete stub module has no attribute '{attr}'")
- argcomplete = StubModule() # type:ignore
- CompletionFinder = object # type:ignore
+ argcomplete = StubModule() # type:ignore[assignment]
+ CompletionFinder = object # type:ignore[assignment, misc]
def get_argcomplete_cwords() -> t.Optional[t.List[str]]:
@@ -45,9 +45,7 @@ def get_argcomplete_cwords() -> t.Optional[t.List[str]]:
cword_suffix,
comp_words,
last_wordbreak_pos,
- ) = argcomplete.split_line( # type:ignore
- comp_line, comp_point
- )
+ ) = argcomplete.split_line(comp_line, comp_point)
except ModuleNotFoundError:
return None
@@ -75,9 +73,7 @@ def increment_argcomplete_index() -> None:
os.environ["_ARGCOMPLETE"] = str(int(os.environ["_ARGCOMPLETE"]) + 1)
except Exception:
try:
- argcomplete.debug( # type:ignore
- "Unable to increment $_ARGCOMPLETE", os.environ["_ARGCOMPLETE"]
- )
+ argcomplete.debug("Unable to increment $_ARGCOMPLETE", os.environ["_ARGCOMPLETE"])
except (KeyError, ModuleNotFoundError):
pass
@@ -153,7 +149,7 @@ class ExtendedCompletionFinder(CompletionFinder):
def _get_completions(
self, comp_words: t.List[str], cword_prefix: str, *args: t.Any
) -> t.List[str]:
- """Overriden to dynamically append --Class.trait arguments if appropriate
+ """Overridden to dynamically append --Class.trait arguments if appropriate
Warning:
This does not (currently) support completions of the form
@@ -200,7 +196,7 @@ class ExtendedCompletionFinder(CompletionFinder):
# Instead, check if comp_words only consists of the script,
# if so check if any subcommands start with cword_prefix.
if self.subcommands and len(comp_words) == 1:
- argcomplete.debug("Adding subcommands for", cword_prefix) # type:ignore
+ argcomplete.debug("Adding subcommands for", cword_prefix)
completions.extend(subc for subc in self.subcommands if subc.startswith(cword_prefix))
return completions
@@ -208,7 +204,7 @@ class ExtendedCompletionFinder(CompletionFinder):
def _get_option_completions(
self, parser: argparse.ArgumentParser, cword_prefix: str
) -> t.List[str]:
- """Overriden to add --Class. completions when appropriate"""
+ """Overridden to add --Class. completions when appropriate"""
completions: t.List[str]
completions = super()._get_option_completions(parser, cword_prefix)
if cword_prefix.endswith("."):
@@ -217,7 +213,7 @@ class ExtendedCompletionFinder(CompletionFinder):
matched_completions = self.match_class_completions(cword_prefix)
if len(matched_completions) > 1:
completions.extend(opt for cls, opt in matched_completions)
- # If there is exactly one match, we would expect it to have aleady
+ # If there is exactly one match, we would expect it to have already
# been handled by the options dynamically added in _get_completions().
# However, maybe there's an edge cases missed here, for example if the
# matched class has no configurable traits.
diff --git a/contrib/python/traitlets/py3/traitlets/config/configurable.py b/contrib/python/traitlets/py3/traitlets/config/configurable.py
index 77b4214e45..776138f4b3 100644
--- a/contrib/python/traitlets/py3/traitlets/config/configurable.py
+++ b/contrib/python/traitlets/py3/traitlets/config/configurable.py
@@ -123,7 +123,7 @@ class Configurable(HasTraits):
setattr(self, name, kwargs[name])
# -------------------------------------------------------------------------
- # Static trait notifiations
+ # Static trait notifications
# -------------------------------------------------------------------------
@classmethod
@@ -161,7 +161,10 @@ class Configurable(HasTraits):
return my_config
def _load_config(
- self, cfg: Config, section_names: list[str] | None = None, traits: list[str] | None = None
+ self,
+ cfg: Config,
+ section_names: list[str] | None = None,
+ traits: dict[str, TraitType] | None = None,
) -> None:
"""load traits from a Config object"""
@@ -344,6 +347,7 @@ class Configurable(HasTraits):
if the defining class is not in `classes`.
"""
defining_cls = cls
+ assert trait.name is not None
for parent in cls.mro():
if (
issubclass(parent, Configurable)
@@ -382,9 +386,9 @@ class Configurable(HasTraits):
desc = desc.default_value
if not desc:
# no description from trait, use __doc__
- desc = getattr(cls, "__doc__", "")
+ desc = getattr(cls, "__doc__", "") # type:ignore[arg-type]
if desc:
- lines.append(c(desc))
+ lines.append(c(desc)) # type:ignore[arg-type]
lines.append("")
for name, trait in sorted(cls.class_traits(config=True).items()):
@@ -424,12 +428,14 @@ class Configurable(HasTraits):
for _, trait in sorted(cls.class_traits(config=True).items()):
ttype = trait.__class__.__name__
+ if not trait.name:
+ continue
termline = classname + "." + trait.name
# Choices or type
if "Enum" in ttype:
# include Enum choices
- termline += " : " + trait.info_rst()
+ termline += " : " + trait.info_rst() # type:ignore[attr-defined]
else:
termline += " : " + ttype
lines.append(termline)
@@ -540,7 +546,7 @@ class SingletonConfigurable(LoggingConfigurable):
if isinstance(subclass._instance, cls):
# only clear instances that are instances
# of the calling class
- subclass._instance = None
+ subclass._instance = None # type:ignore[unreachable]
@classmethod
def instance(cls: type[CT], *args: t.Any, **kwargs: t.Any) -> CT:
@@ -562,7 +568,7 @@ class SingletonConfigurable(LoggingConfigurable):
>>> foo == Foo.instance()
True
- Create a subclass that is retrived using the base class instance::
+ Create a subclass that is retrieved using the base class instance::
>>> class Bar(SingletonConfigurable): pass
>>> class Bam(Bar): pass
diff --git a/contrib/python/traitlets/py3/traitlets/config/loader.py b/contrib/python/traitlets/py3/traitlets/config/loader.py
index 437c8c17cd..dc0add5704 100644
--- a/contrib/python/traitlets/py3/traitlets/config/loader.py
+++ b/contrib/python/traitlets/py3/traitlets/config/loader.py
@@ -176,7 +176,7 @@ class LazyConfigValue(HasTraits):
after applying any insert / extend / update changes
"""
if self._value is not None:
- return self._value
+ return self._value # type:ignore[unreachable]
value = copy.deepcopy(initial)
if isinstance(value, list):
for idx, obj in self._inserts:
@@ -860,7 +860,7 @@ class ArgParseConfigLoader(CommandLineConfigLoader):
arguments from. If not given, the instance's self.argv attribute
(given at construction time) is used.
flags
- Deprecated in traitlets 5.0, instanciate the config loader with the flags.
+ Deprecated in traitlets 5.0, instantiate the config loader with the flags.
"""
@@ -914,7 +914,7 @@ class ArgParseConfigLoader(CommandLineConfigLoader):
for alias, alias_target in self.aliases.items():
if alias in self.flags:
continue
- if not isinstance(alias, tuple):
+ if not isinstance(alias, tuple): # type:ignore[unreachable]
alias = (alias,) # type:ignore[assignment]
for al in alias:
if len(al) == 1:
@@ -1057,7 +1057,9 @@ class KVArgParseConfigLoader(ArgParseConfigLoader):
action = paa(*keys, **argparse_kwds)
if argcompleter is not None:
# argcomplete's completers are callables returning list of completion strings
- action.completer = functools.partial(argcompleter, key=key) # type: ignore
+ action.completer = functools.partial( # type:ignore[attr-defined]
+ argcompleter, key=key
+ )
def _convert_to_config(self):
"""self.parsed_data->self.config, parse unrecognized extra args via KVLoader."""
diff --git a/contrib/python/traitlets/py3/traitlets/traitlets.py b/contrib/python/traitlets/py3/traitlets/traitlets.py
index 50d6face52..55628c2393 100644
--- a/contrib/python/traitlets/py3/traitlets/traitlets.py
+++ b/contrib/python/traitlets/py3/traitlets/traitlets.py
@@ -234,7 +234,7 @@ def getmembers(object, predicate=None):
This is useful when there are descriptor based attributes that for
some reason raise AttributeError even though they exist. This happens
- in zope.inteface with the __provides__ attribute.
+ in zope.interface with the __provides__ attribute.
"""
results = []
for key in dir(object):
@@ -437,9 +437,9 @@ class BaseDescriptor:
"""
name: str | None = None
- this_class: type[t.Any] | None = None
+ this_class: type[HasTraits] | None = None
- def class_init(self, cls, name):
+ def class_init(self, cls: type[HasTraits], name: str | None) -> None:
"""Part of the initialization which may depend on the underlying
HasDescriptors class.
@@ -452,18 +452,18 @@ class BaseDescriptor:
self.this_class = cls
self.name = name
- def subclass_init(self, cls):
+ def subclass_init(self, cls: type[HasTraits]) -> None:
# Instead of HasDescriptors.setup_instance calling
# every instance_init, we opt in by default.
# This gives descriptors a change to opt out for
# performance reasons.
# Because most traits do not need instance_init,
# and it will otherwise be called for every HasTrait instance
- # beging created, this otherwise gives a significant performance
+ # being created, this otherwise gives a significant performance
# pentalty. Most TypeTraits in traitlets opt out.
cls._instance_inits.append(self.instance_init)
- def instance_init(self, obj):
+ def instance_init(self, obj: t.Any) -> None:
"""Part of the initialization which may depend on the underlying
HasDescriptors instance.
@@ -497,7 +497,7 @@ class TraitType(BaseDescriptor, t.Generic[G, S]):
allow_none: bool = False
read_only: bool = False
info_text: str = "any value"
- default_value: t.Any | None = Undefined
+ default_value: t.Any = Undefined
def __init__(
self: TraitType[G, S],
@@ -567,7 +567,7 @@ class TraitType(BaseDescriptor, t.Generic[G, S]):
if help is not None:
self.metadata["help"] = help
- def from_string(self, s):
+ def from_string(self, s: str) -> G | None:
"""Get a value from a config string
such as an environment variable or CLI arguments.
@@ -581,9 +581,9 @@ class TraitType(BaseDescriptor, t.Generic[G, S]):
"""
if self.allow_none and s == "None":
return None
- return s
+ return s # type:ignore[return-value]
- def default(self, obj=None):
+ def default(self, obj: t.Any = None) -> G | None:
"""The default generator for this trait
Notes
@@ -599,7 +599,7 @@ class TraitType(BaseDescriptor, t.Generic[G, S]):
# Undefined will raise in TraitType.get
return self.default_value
- def get_default_value(self):
+ def get_default_value(self) -> G | None:
"""DEPRECATED: Retrieve the static default value for this trait.
Use self.default_value instead
"""
@@ -610,7 +610,7 @@ class TraitType(BaseDescriptor, t.Generic[G, S]):
)
return self.default_value
- def init_default_value(self, obj):
+ def init_default_value(self, obj: t.Any) -> G:
"""DEPRECATED: Set the static default value for the trait type."""
warn(
"init_default_value is deprecated in traitlets 4.0, and may be removed in the future",
@@ -622,8 +622,9 @@ class TraitType(BaseDescriptor, t.Generic[G, S]):
return value
def get(self, obj: HasTraits, cls: t.Any = None) -> G | None:
+ assert self.name is not None
try:
- value = obj._trait_values[self.name] # type: ignore
+ value = obj._trait_values[self.name] # type: ignore[index]
except KeyError:
# Check for a dynamic initializer.
default = obj.trait_defaults(self.name)
@@ -643,7 +644,7 @@ class TraitType(BaseDescriptor, t.Generic[G, S]):
value = self._validate(obj, default)
finally:
obj._cross_validation_lock = _cross_validation_lock
- obj._trait_values[self.name] = value # type: ignore
+ obj._trait_values[self.name] = value # type: ignore[index]
obj._notify_observers(
Bunch(
name=self.name,
@@ -652,12 +653,12 @@ class TraitType(BaseDescriptor, t.Generic[G, S]):
type="default",
)
)
- return value # type: ignore
+ return value
except Exception as e:
# This should never be reached.
raise TraitError("Unexpected error in TraitType: default value not set properly") from e
else:
- return value # type: ignore
+ return value
if t.TYPE_CHECKING:
# This gives ok type information, but not specific enough (e.g. it will)
@@ -718,8 +719,9 @@ class TraitType(BaseDescriptor, t.Generic[G, S]):
else:
return t.cast(G, self.get(obj, cls)) # the G should encode the Optional
- def set(self, obj, value):
+ def set(self, obj: HasTraits, value: S) -> None:
new_value = self._validate(obj, value)
+ assert self.name is not None
try:
old_value = obj._trait_values[self.name]
except KeyError:
@@ -804,7 +806,7 @@ class TraitType(BaseDescriptor, t.Generic[G, S]):
the deepest).
info : str (default: None)
A description of the expected value. By
- default this is infered from this trait's
+ default this is inferred from this trait's
``info`` method.
"""
if error is not None:
@@ -965,7 +967,7 @@ class MetaHasDescriptors(type):
instantiated and sets their name attribute.
"""
- def __new__(mcls, name, bases, classdict): # noqa
+ def __new__(mcls, name, bases, classdict, **kwds): # noqa
"""Create the HasDescriptors class."""
for k, v in classdict.items():
# ----------------------------------------------------------------
@@ -981,11 +983,11 @@ class MetaHasDescriptors(type):
classdict[k] = v()
# ----------------------------------------------------------------
- return super().__new__(mcls, name, bases, classdict)
+ return super().__new__(mcls, name, bases, classdict, **kwds)
- def __init__(cls, name: str, bases: t.Any, classdict: t.Any) -> None:
+ def __init__(cls, name: str, bases: t.Any, classdict: t.Any, **kwds) -> None:
"""Finish initializing the HasDescriptors class."""
- super().__init__(name, bases, classdict)
+ super().__init__(name, bases, classdict, **kwds)
cls.setup_class(classdict)
def setup_class(cls, classdict):
@@ -999,11 +1001,11 @@ class MetaHasDescriptors(type):
cls._instance_inits = []
for k, v in classdict.items():
if isinstance(v, BaseDescriptor):
- v.class_init(cls, k)
+ v.class_init(cls, k) # type:ignore[arg-type]
for _, v in getmembers(cls):
if isinstance(v, BaseDescriptor):
- v.subclass_init(cls)
+ v.subclass_init(cls) # type:ignore[arg-type]
cls._descriptors.append(v)
@@ -1143,8 +1145,8 @@ def observe_compat(func: FuncT) -> FuncT:
def compatible_observer(
self: t.Any, change_or_name: str, old: t.Any = Undefined, new: t.Any = Undefined
) -> t.Any:
- if isinstance(change_or_name, dict):
- change = Bunch(change_or_name)
+ if isinstance(change_or_name, dict): # type:ignore[unreachable]
+ change = Bunch(change_or_name) # type:ignore[unreachable]
else:
clsname = self.__class__.__name__
warn(
@@ -1414,7 +1416,7 @@ class HasTraits(HasDescriptors, metaclass=MetaHasTraits):
stacklevel=2,
)
- def __getstate__(self):
+ def __getstate__(self) -> dict[str, t.Any]:
d = self.__dict__.copy()
# event handlers stored on an instance are
# expected to be reinstantiated during a
@@ -1426,7 +1428,7 @@ class HasTraits(HasDescriptors, metaclass=MetaHasTraits):
return d
- def __setstate__(self, state):
+ def __setstate__(self, state: dict[str, t.Any]) -> None:
self.__dict__ = state.copy()
# event handlers are reassigned to self
@@ -1507,7 +1509,7 @@ class HasTraits(HasDescriptors, metaclass=MetaHasTraits):
self.set_trait(name, value)
except TraitError as e:
# Roll back in case of TraitError during final cross validation.
- self.notify_change = lambda x: None # type:ignore[method-assign]
+ self.notify_change = lambda x: None # type:ignore[method-assign, assignment]
for name, changes in cache.items():
for change in changes[::-1]:
# TODO: Separate in a rollback function per notification type.
@@ -1539,15 +1541,15 @@ class HasTraits(HasDescriptors, metaclass=MetaHasTraits):
)
)
- def notify_change(self, change):
+ def notify_change(self, change: Bunch) -> None:
"""Notify observers of a change event"""
return self._notify_observers(change)
- def _notify_observers(self, event):
+ def _notify_observers(self, event: Bunch) -> None:
"""Notify observers of any event"""
if not isinstance(event, Bunch):
# cast to bunch if given a dict
- event = Bunch(event)
+ event = Bunch(event) # type:ignore[unreachable]
name, type = event['name'], event['type']
callables = []
@@ -1756,7 +1758,7 @@ class HasTraits(HasDescriptors, metaclass=MetaHasTraits):
for name in names:
self._trait_validators[name] = handler
- def add_traits(self, **traits):
+ def add_traits(self, **traits: t.Any) -> None:
"""Dynamically add trait attributes to the HasTraits instance."""
cls = self.__class__
attrs = {"__module__": cls.__module__}
@@ -1768,7 +1770,7 @@ class HasTraits(HasDescriptors, metaclass=MetaHasTraits):
for trait in traits.values():
trait.instance_init(self)
- def set_trait(self, name, value):
+ def set_trait(self, name: str, value: t.Any) -> None:
"""Forcibly sets trait attribute, including read-only attributes."""
cls = self.__class__
if not self.has_trait(name):
@@ -1777,7 +1779,7 @@ class HasTraits(HasDescriptors, metaclass=MetaHasTraits):
getattr(cls, name).set(self, value)
@classmethod
- def class_trait_names(cls, **metadata):
+ def class_trait_names(cls: type[HasTraits], **metadata: t.Any) -> list[str]:
"""Get a list of all the names of this class' traits.
This method is just like the :meth:`trait_names` method,
@@ -1786,7 +1788,7 @@ class HasTraits(HasDescriptors, metaclass=MetaHasTraits):
return list(cls.class_traits(**metadata))
@classmethod
- def class_traits(cls, **metadata):
+ def class_traits(cls: type[HasTraits], **metadata: t.Any) -> dict[str, TraitType]:
"""Get a ``dict`` of all the traits of this class. The dictionary
is keyed on the name and the values are the TraitType objects.
@@ -1820,7 +1822,7 @@ class HasTraits(HasDescriptors, metaclass=MetaHasTraits):
return result
@classmethod
- def class_own_traits(cls, **metadata):
+ def class_own_traits(cls: type[HasTraits], **metadata: t.Any) -> dict[str, TraitType]:
"""Get a dict of all the traitlets defined on this class, not a parent.
Works like `class_traits`, except for excluding traits from parents.
@@ -1832,11 +1834,11 @@ class HasTraits(HasDescriptors, metaclass=MetaHasTraits):
if getattr(sup, n, None) is not t
}
- def has_trait(self, name):
+ def has_trait(self, name: str) -> bool:
"""Returns True if the object has a trait with the specified name."""
return name in self._traits
- def trait_has_value(self, name):
+ def trait_has_value(self, name: str) -> bool:
"""Returns True if the specified trait has a value.
This will return false even if ``getattr`` would return a
@@ -1851,14 +1853,15 @@ class HasTraits(HasDescriptors, metaclass=MetaHasTraits):
class MyClass(HasTraits):
i = Int()
+
mc = MyClass()
assert not mc.trait_has_value("i")
- mc.i # generates a default value
+ mc.i # generates a default value
assert mc.trait_has_value("i")
"""
return name in self._trait_values
- def trait_values(self, **metadata):
+ def trait_values(self, **metadata: t.Any) -> dict[str, t.Any]:
"""A ``dict`` of trait names and their values.
The metadata kwargs allow functions to be passed in which
@@ -1892,7 +1895,7 @@ class HasTraits(HasDescriptors, metaclass=MetaHasTraits):
return getattr(self.__class__, method_name)
return self._all_trait_default_generators[name]
- def trait_defaults(self, *names, **metadata):
+ def trait_defaults(self, *names: str, **metadata: t.Any) -> dict[str, t.Any]:
"""Return a trait's default value or a dictionary of them
Notes
@@ -1914,11 +1917,11 @@ class HasTraits(HasDescriptors, metaclass=MetaHasTraits):
defaults[n] = self._get_trait_default_generator(n)(self)
return defaults
- def trait_names(self, **metadata):
+ def trait_names(self, **metadata: t.Any) -> list[str]:
"""Get a list of all the names of this class' traits."""
return list(self.traits(**metadata))
- def traits(self, **metadata):
+ def traits(self, **metadata: t.Any) -> dict[str, TraitType]:
"""Get a ``dict`` of all the traits of this class. The dictionary
is keyed on the name and the values are the TraitType objects.
@@ -1949,7 +1952,7 @@ class HasTraits(HasDescriptors, metaclass=MetaHasTraits):
return result
- def trait_metadata(self, traitname, key, default=None):
+ def trait_metadata(self, traitname: str, key: str, default: t.Any = None) -> t.Any:
"""Get metadata values for trait by key."""
try:
trait = getattr(self.__class__, traitname)
@@ -1964,7 +1967,7 @@ class HasTraits(HasDescriptors, metaclass=MetaHasTraits):
return trait.metadata.get(key, default)
@classmethod
- def class_own_trait_events(cls, name):
+ def class_own_trait_events(cls: type[HasTraits], name: str) -> dict[str, EventHandler]:
"""Get a dict of all event handlers defined on this class, not a parent.
Works like ``event_handlers``, except for excluding traits from parents.
@@ -1977,7 +1980,7 @@ class HasTraits(HasDescriptors, metaclass=MetaHasTraits):
}
@classmethod
- def trait_events(cls, name=None):
+ def trait_events(cls: type[HasTraits], name: str | None = None) -> dict[str, EventHandler]:
"""Get a ``dict`` of all the event handlers of this class.
Parameters
@@ -3670,7 +3673,12 @@ class Set(Container[t.Set[t.Any]]):
def set(self, obj, value):
if isinstance(value, str):
- return super().set(obj, [value])
+ return super().set(
+ obj,
+ set(
+ value,
+ ),
+ )
else:
return super().set(obj, value)
@@ -3993,7 +4001,7 @@ class Dict(Instance[t.Dict[t.Any, t.Any]]):
self.element_error(obj, v, active_value_trait, "Values")
validated[key] = v
- return self.klass(validated) # type:ignore
+ return self.klass(validated) # type:ignore[misc,operator]
def class_init(self, cls, name):
if isinstance(self._value_trait, TraitType):
@@ -4174,19 +4182,22 @@ class UseEnum(TraitType[t.Any, t.Any]):
import enum
from traitlets import HasTraits, UseEnum
+
class Color(enum.Enum):
- red = 1 # -- IMPLICIT: default_value
+ red = 1 # -- IMPLICIT: default_value
blue = 2
green = 3
+
class MyEntity(HasTraits):
color = UseEnum(Color, default_value=Color.blue)
+
entity = MyEntity(color=Color.red)
- entity.color = Color.green # USE: Enum-value (preferred)
- entity.color = "green" # USE: name (as string)
+ entity.color = Color.green # USE: Enum-value (preferred)
+ entity.color = "green" # USE: name (as string)
entity.color = "Color.green" # USE: scoped-name (as string)
- entity.color = 3 # USE: number (as int)
+ entity.color = 3 # USE: number (as int)
assert entity.color is Color.green
"""
diff --git a/contrib/python/traitlets/py3/traitlets/utils/__init__.py b/contrib/python/traitlets/py3/traitlets/utils/__init__.py
index e8ee7f9856..2695dc7335 100644
--- a/contrib/python/traitlets/py3/traitlets/utils/__init__.py
+++ b/contrib/python/traitlets/py3/traitlets/utils/__init__.py
@@ -16,7 +16,7 @@ def filefind(filename: str, path_dirs: Sequence[str] | None = None) -> str:
"""Find a file by looking through a sequence of paths.
This iterates through a sequence of paths looking for a file and returns
- the full, absolute path of the first occurence of the file. If no set of
+ the full, absolute path of the first occurrence of the file. If no set of
path dirs is given, the filename is tested as is, after running through
:func:`expandvars` and :func:`expanduser`. Thus a simple call::
diff --git a/contrib/python/traitlets/py3/traitlets/utils/decorators.py b/contrib/python/traitlets/py3/traitlets/utils/decorators.py
index dedbaad193..8090636bc8 100644
--- a/contrib/python/traitlets/py3/traitlets/utils/decorators.py
+++ b/contrib/python/traitlets/py3/traitlets/utils/decorators.py
@@ -55,9 +55,7 @@ def signature_has_traits(cls: Type[T]) -> Type[T]:
# because it can't accept traits as keyword arguments
if old_var_keyword_parameter is None:
raise RuntimeError(
- "The {} constructor does not take **kwargs, which means that the signature can not be expanded with trait names".format(
- cls
- )
+ f"The {cls} constructor does not take **kwargs, which means that the signature can not be expanded with trait names"
)
new_parameters = []
diff --git a/contrib/python/traitlets/py3/traitlets/utils/descriptions.py b/contrib/python/traitlets/py3/traitlets/utils/descriptions.py
index c068ecdba5..785ec58116 100644
--- a/contrib/python/traitlets/py3/traitlets/utils/descriptions.py
+++ b/contrib/python/traitlets/py3/traitlets/utils/descriptions.py
@@ -20,7 +20,7 @@ def describe(
article : str or None
A definite or indefinite article. If the article is
indefinite (i.e. "a" or "an") the appropriate one
- will be infered. Thus, the arguments of ``describe``
+ will be inferred. Thus, the arguments of ``describe``
can themselves represent what the resulting string
will actually look like. If None, then no article
will be prepended to the result. For non-articled
@@ -31,7 +31,7 @@ def describe(
name : str or None (default: None)
Only applies when ``article`` is "the" - this
``name`` is a definite reference to the value.
- By default one will be infered from the value's
+ By default one will be inferred from the value's
type and repr methods.
verbose : bool (default: False)
Whether the name should be concise or verbose. When
@@ -145,7 +145,7 @@ def class_of(value: Any) -> Any:
def add_article(name: str, definite: bool = False, capital: bool = False) -> str:
"""Returns the string with a prepended article.
- The input does not need to begin with a charater.
+ The input does not need to begin with a character.
Parameters
----------
diff --git a/contrib/python/traitlets/py3/ya.make b/contrib/python/traitlets/py3/ya.make
index ff8ebca152..50dfd2c1bd 100644
--- a/contrib/python/traitlets/py3/ya.make
+++ b/contrib/python/traitlets/py3/ya.make
@@ -4,7 +4,7 @@ PY3_LIBRARY()
PROVIDES(python_traitlets)
-VERSION(5.11.2)
+VERSION(5.12.0)
LICENSE(BSD-3-Clause)