Skip to content

Commit 6d7ccc4

Browse files
committed
Upgrade various type annotations
1 parent 7050be1 commit 6d7ccc4

File tree

9 files changed

+47
-48
lines changed

9 files changed

+47
-48
lines changed

pyproject.toml

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -186,8 +186,7 @@ ignore = [
186186
"S105", "S106", # Possible hardcoded password
187187
"S110", # S110 `try`-`except`-`pass` detected
188188
"RUF012", # Mutable class attributes should be annotated with `typing.ClassVar`
189-
"UP006", # non-pep585-annotation
190-
"UP007", # non-pep604-annotation
189+
"UP038", # non-pep604-isinstance (removed in ruff 0.13.0)
191190
"ARG001", "ARG002", # Unused function argument
192191
"RET503", # Missing explicit `return` at the end of function
193192
"RET505", # Unnecessary `else` after `return` statement

tests/config/test_application.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -66,7 +66,7 @@ class MyApp(Application):
6666
help="Should print a warning if `MyApp.warn-typo=...` command is passed",
6767
)
6868

69-
aliases: t.Dict[t.Any, t.Any] = {}
69+
aliases: dict[t.Any, t.Any] = {}
7070
aliases.update(Application.aliases)
7171
aliases.update(
7272
{
@@ -83,7 +83,7 @@ class MyApp(Application):
8383
}
8484
)
8585

86-
flags: t.Dict[t.Any, t.Any] = {}
86+
flags: dict[t.Any, t.Any] = {}
8787
flags.update(Application.flags)
8888
flags.update(
8989
{

tests/config/test_argcomplete.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,7 @@
2323
class ArgcompleteApp(Application):
2424
"""Override loader to pass through kwargs for argcomplete testing"""
2525

26-
argcomplete_kwargs: t.Dict[str, t.Any]
26+
argcomplete_kwargs: dict[str, t.Any]
2727

2828
def __init__(self, *args, **kwargs):
2929
# For subcommands, inherit argcomplete_kwargs from parent app
@@ -99,9 +99,9 @@ def run_completer(
9999
self,
100100
app: ArgcompleteApp,
101101
command: str,
102-
point: t.Union[str, int, None] = None,
102+
point: str | int | None = None,
103103
**kwargs: t.Any,
104-
) -> t.List[str]:
104+
) -> list[str]:
105105
"""Mostly borrowed from argcomplete's unit tests
106106
107107
Modified to take an application instead of an ArgumentParser

tests/test_traitlets.py

Lines changed: 9 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -69,7 +69,7 @@
6969

7070
def change_dict(*ordered_values):
7171
change_names = ("name", "old", "new", "owner", "type")
72-
return dict(zip(change_names, ordered_values))
72+
return dict(zip(change_names, ordered_values, strict=True))
7373

7474

7575
# -----------------------------------------------------------------------------
@@ -1650,7 +1650,7 @@ class ListTrait(HasTraits):
16501650
class TestList(TraitTestBase):
16511651
obj = ListTrait()
16521652

1653-
_default_value: t.List[t.Any] = []
1653+
_default_value: list[t.Any] = []
16541654
_good_values = [[], [1], list(range(10)), (1, 2)]
16551655
_bad_values = [10, [1, "a"], "a"]
16561656

@@ -1667,7 +1667,7 @@ class SetTrait(HasTraits):
16671667
class TestSet(TraitTestBase):
16681668
obj = SetTrait()
16691669

1670-
_default_value: t.Set[str] = set()
1670+
_default_value: set[str] = set()
16711671
_good_values = [{"a", "b"}, "ab"]
16721672
_bad_values = [1]
16731673

@@ -1689,7 +1689,7 @@ class NoneInstanceListTrait(HasTraits):
16891689
class TestNoneInstanceList(TraitTestBase):
16901690
obj = NoneInstanceListTrait()
16911691

1692-
_default_value: t.List[t.Any] = []
1692+
_default_value: list[t.Any] = []
16931693
_good_values = [[Foo(), Foo()], []]
16941694
_bad_values = [[None], [Foo(), None]]
16951695

@@ -1705,7 +1705,7 @@ def test_klass(self):
17051705
"""Test that the instance klass is properly assigned."""
17061706
self.assertIs(self.obj.traits()["value"]._trait.klass, Foo)
17071707

1708-
_default_value: t.List[t.Any] = []
1708+
_default_value: list[t.Any] = []
17091709
_good_values = [[Foo(), Foo()], []]
17101710
_bad_values = [
17111711
[
@@ -1725,7 +1725,7 @@ class UnionListTrait(HasTraits):
17251725
class TestUnionListTrait(TraitTestBase):
17261726
obj = UnionListTrait()
17271727

1728-
_default_value: t.List[t.Any] = []
1728+
_default_value: list[t.Any] = []
17291729
_good_values = [[True, 1], [False, True]]
17301730
_bad_values = [[1, "True"], False]
17311731

@@ -1881,7 +1881,7 @@ class DictTrait(HasTraits):
18811881

18821882

18831883
def test_dict_assignment():
1884-
d: t.Dict[str, int] = {}
1884+
d: dict[str, int] = {}
18851885
c = DictTrait()
18861886
c.value = d
18871887
d["a"] = 5
@@ -2504,7 +2504,7 @@ def test_klass(self):
25042504
"""Test that the instance klass is properly assigned."""
25052505
self.assertIs(self.obj.traits()["value"]._trait.klass, ForwardDeclaredBar)
25062506

2507-
_default_value: t.List[t.Any] = []
2507+
_default_value: list[t.Any] = []
25082508
_good_values = [
25092509
[ForwardDeclaredBar(), ForwardDeclaredBarSub()],
25102510
[],
@@ -2527,7 +2527,7 @@ def test_klass(self):
25272527
"""Test that the instance klass is properly assigned."""
25282528
self.assertIs(self.obj.traits()["value"]._trait.klass, ForwardDeclaredBar)
25292529

2530-
_default_value: t.List[t.Any] = []
2530+
_default_value: list[t.Any] = []
25312531
_good_values = [
25322532
[ForwardDeclaredBar, ForwardDeclaredBarSub],
25332533
[],

traitlets/config/application.py

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -98,9 +98,9 @@
9898

9999
T = t.TypeVar("T", bound=t.Callable[..., t.Any])
100100
AnyLogger = t.Union[logging.Logger, "logging.LoggerAdapter[t.Any]"]
101-
StrDict = t.Dict[str, t.Any]
102-
ArgvType = t.Optional[t.List[str]]
103-
ClassesType = t.List[t.Type[Configurable]]
101+
StrDict = dict[str, t.Any]
102+
ArgvType = list[str] | None
103+
ClassesType = list[type[Configurable]]
104104

105105

106106
def catch_config_error(method: T) -> T:
@@ -520,7 +520,7 @@ def emit_alias_help(self) -> t.Generator[str, None, None]:
520520
for cls in self.classes:
521521
# include all parents (up to, but excluding Configurable) in available names
522522
for c in cls.mro()[:-3]:
523-
classdict[c.__name__] = t.cast(t.Type[Configurable], c)
523+
classdict[c.__name__] = t.cast(type[Configurable], c)
524524

525525
fhelp: str | None
526526
for alias, longname in self.aliases.items():
@@ -931,7 +931,7 @@ def _load_config_files(
931931
if log:
932932
log.debug("Loaded config file: %s", loader.full_filename)
933933
if config:
934-
for filename, earlier_config in zip(filenames, loaded):
934+
for filename, earlier_config in zip(filenames, loaded, strict=True):
935935
collisions = earlier_config.collisions(config)
936936
if collisions and log:
937937
log.warning(

traitlets/config/argcomplete_config.py

Lines changed: 9 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,7 @@ def __getattr__(self, attr: str) -> t.Any:
2424
CompletionFinder = object # type:ignore[assignment, misc]
2525

2626

27-
def get_argcomplete_cwords() -> t.Optional[t.List[str]]:
27+
def get_argcomplete_cwords() -> list[str] | None:
2828
"""Get current words prior to completion point
2929
3030
This is normally done in the `argcomplete.CompletionFinder` constructor,
@@ -37,7 +37,7 @@ def get_argcomplete_cwords() -> t.Optional[t.List[str]]:
3737
comp_line = os.environ["COMP_LINE"]
3838
comp_point = int(os.environ["COMP_POINT"])
3939
# argcomplete.debug("splitting COMP_LINE for:", comp_line, comp_point)
40-
comp_words: t.List[str]
40+
comp_words: list[str]
4141
try:
4242
(
4343
cword_prequote,
@@ -98,10 +98,10 @@ class in `Application.classes` that could complete the current option.
9898
"""
9999

100100
_parser: argparse.ArgumentParser
101-
config_classes: t.List[t.Any] = [] # Configurables
102-
subcommands: t.List[str] = []
101+
config_classes: list[t.Any] = [] # Configurables
102+
subcommands: list[str] = []
103103

104-
def match_class_completions(self, cword_prefix: str) -> t.List[t.Tuple[t.Any, str]]:
104+
def match_class_completions(self, cword_prefix: str) -> list[tuple[t.Any, str]]:
105105
"""Match the word to be completed against our Configurable classes
106106
107107
Check if cword_prefix could potentially match against --{class}. for any class
@@ -146,9 +146,7 @@ def inject_class_to_parser(self, cls: t.Any) -> None:
146146
except AttributeError:
147147
pass
148148

149-
def _get_completions(
150-
self, comp_words: t.List[str], cword_prefix: str, *args: t.Any
151-
) -> t.List[str]:
149+
def _get_completions(self, comp_words: list[str], cword_prefix: str, *args: t.Any) -> list[str]:
152150
"""Overridden to dynamically append --Class.trait arguments if appropriate
153151
154152
Warning:
@@ -187,7 +185,7 @@ def _get_completions(
187185
self.inject_class_to_parser(matched_cls)
188186
break
189187

190-
completions: t.List[str]
188+
completions: list[str]
191189
completions = super()._get_completions(comp_words, cword_prefix, *args) # type:ignore[no-untyped-call]
192190

193191
# For subcommand-handling: it is difficult to get this to work
@@ -203,9 +201,9 @@ def _get_completions(
203201

204202
def _get_option_completions(
205203
self, parser: argparse.ArgumentParser, cword_prefix: str
206-
) -> t.List[str]:
204+
) -> list[str]:
207205
"""Overridden to add --Class. completions when appropriate"""
208-
completions: t.List[str]
206+
completions: list[str]
209207
completions = super()._get_option_completions(parser, cword_prefix) # type:ignore[no-untyped-call]
210208
if cword_prefix.endswith("."):
211209
return completions

traitlets/config/configurable.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -32,7 +32,7 @@
3232
# -----------------------------------------------------------------------------
3333

3434
if t.TYPE_CHECKING:
35-
LoggerType = t.Union[logging.Logger, logging.LoggerAdapter[t.Any]]
35+
LoggerType = logging.Logger | logging.LoggerAdapter[t.Any]
3636
else:
3737
LoggerType = t.Any
3838

traitlets/config/loader.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -420,7 +420,7 @@ def __repr__(self) -> str:
420420
return f"{self.__class__.__name__}({self._super_repr()})"
421421

422422

423-
class DeferredConfigList(t.List[t.Any], DeferredConfig):
423+
class DeferredConfigList(list[t.Any], DeferredConfig):
424424
"""Config value for loading config from a list of strings
425425
426426
Interpretation is deferred until it is loaded into the trait.
@@ -791,7 +791,7 @@ def parse_known_args( # type:ignore[override]
791791

792792

793793
# type aliases
794-
SubcommandsDict = t.Dict[str, t.Any]
794+
SubcommandsDict = dict[str, t.Any]
795795

796796

797797
class ArgParseConfigLoader(CommandLineConfigLoader):

traitlets/traitlets.py

Lines changed: 15 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -501,7 +501,9 @@ def instance_init(self, obj: t.Any) -> None:
501501
# see https://peps.python.org/pep-0673/#use-in-generic-classes
502502
# Self = t.TypeVar("Self", bound="TraitType[Any, Any]")
503503
if t.TYPE_CHECKING:
504-
from typing_extensions import Literal, Self
504+
from typing import Literal
505+
506+
from typing_extensions import Self
505507

506508
K = TypeVar("K", default=str)
507509
V = TypeVar("V", default=t.Any)
@@ -2370,7 +2372,7 @@ class ForwardDeclaredInstance(ForwardDeclaredMixin, Instance[T]):
23702372
"""
23712373

23722374

2373-
class This(ClassBasedTraitType[t.Optional[T], t.Optional[T]]):
2375+
class This(ClassBasedTraitType[T | None, T | None]):
23742376
"""A trait for instances of the class containing this trait.
23752377
23762378
Because how how and when class bodies are executed, the ``This``
@@ -2483,7 +2485,7 @@ def from_string(self, s: str) -> t.Any:
24832485
# -----------------------------------------------------------------------------
24842486

24852487

2486-
class Any(TraitType[t.Optional[t.Any], t.Optional[t.Any]]):
2488+
class Any(TraitType[t.Any | None, t.Any | None]):
24872489
"""A trait which allows any value."""
24882490

24892491
if t.TYPE_CHECKING:
@@ -2582,7 +2584,7 @@ def _validate_bounds(
25822584
return value
25832585

25842586

2585-
# I = t.TypeVar('I', t.Optional[int], int)
2587+
# I = t.TypeVar('I', int | None, int)
25862588

25872589

25882590
class Int(TraitType[G, S]):
@@ -2824,7 +2826,7 @@ def validate(self, obj: t.Any, value: t.Any) -> G:
28242826
return _validate_bounds(self, obj, value) # type:ignore[no-any-return]
28252827

28262828

2827-
class Complex(TraitType[complex, t.Union[complex, float, int]]):
2829+
class Complex(TraitType[complex, complex | float | int]):
28282830
"""A trait for complex numbers."""
28292831

28302832
default_value = 0.0 + 0.0j
@@ -3332,7 +3334,7 @@ def validate(self, obj: t.Any, value: t.Any) -> G:
33323334
choices = self.values or []
33333335
matches = [match_func(value, conv_func(c)) for c in choices] # type:ignore[no-untyped-call]
33343336
if sum(matches) == 1:
3335-
for v, m in zip(choices, matches):
3337+
for v, m in zip(choices, matches, strict=True):
33363338
if m:
33373339
return v
33383340

@@ -3580,16 +3582,16 @@ def item_from_string(self, s: str, index: int | None = None) -> T | str:
35803582
return s
35813583

35823584

3583-
class List(Container[t.List[T]]):
3585+
class List(Container[list[T]]):
35843586
"""An instance of a Python list."""
35853587

35863588
klass = list # type:ignore[assignment]
35873589
_cast_types: t.Any = (tuple,)
35883590

35893591
def __init__(
35903592
self,
3591-
trait: t.List[T] | t.Tuple[T] | t.Set[T] | Sentinel | TraitType[T, t.Any] | None = None,
3592-
default_value: t.List[T] | t.Tuple[T] | t.Set[T] | Sentinel | None = Undefined,
3593+
trait: list[T] | tuple[T] | set[T] | Sentinel | TraitType[T, t.Any] | None = None,
3594+
default_value: list[T] | tuple[T] | set[T] | Sentinel | None = Undefined,
35933595
minlen: int = 0,
35943596
maxlen: int = sys.maxsize,
35953597
**kwargs: t.Any,
@@ -3645,7 +3647,7 @@ def set(self, obj: t.Any, value: t.Any) -> None:
36453647
return super().set(obj, value)
36463648

36473649

3648-
class Set(Container[t.Set[t.Any]]):
3650+
class Set(Container[set[t.Any]]):
36493651
"""An instance of a Python set."""
36503652

36513653
klass = set
@@ -3720,7 +3722,7 @@ def default_value_repr(self) -> str:
37203722
return "{" + list_repr[1:-1] + "}"
37213723

37223724

3723-
class Tuple(Container[t.Tuple[t.Any, ...]]):
3725+
class Tuple(Container[tuple[t.Any, ...]]):
37243726
"""An instance of a Python tuple."""
37253727

37263728
klass = tuple
@@ -3826,7 +3828,7 @@ def validate_elements(self, obj: t.Any, value: t.Any) -> t.Any:
38263828
raise TraitError(e)
38273829

38283830
validated = []
3829-
for trait, v in zip(self._traits, value):
3831+
for trait, v in zip(self._traits, value, strict=True):
38303832
try:
38313833
v = trait._validate(obj, v)
38323834
except TraitError as error:
@@ -4188,7 +4190,7 @@ def from_string(self, s: str) -> G:
41884190
return (ip, port) # type:ignore[return-value]
41894191

41904192

4191-
class CRegExp(TraitType["re.Pattern[t.Any]", t.Union["re.Pattern[t.Any]", str]]):
4193+
class CRegExp(TraitType[re.Pattern[t.Any], re.Pattern[t.Any] | str]):
41924194
"""A casting compiled regular expression trait.
41934195
41944196
Accepts both strings and compiled regular expressions. The resulting

0 commit comments

Comments
 (0)