Skip to content

Commit 945250c

Browse files
Update __new__ method to use Self type for improved type hinting (#918)
Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
1 parent 3c1676d commit 945250c

File tree

1 file changed

+3
-14
lines changed

1 file changed

+3
-14
lines changed

traitlets/traitlets.py

Lines changed: 3 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -1290,11 +1290,7 @@ def class_init(self, cls: type[HasTraits], name: str | None) -> None:
12901290
class HasDescriptors(metaclass=MetaHasDescriptors):
12911291
"""The base class for all classes that have descriptors."""
12921292

1293-
def __new__(*args: t.Any, **kwargs: t.Any) -> t.Any:
1294-
# Pass cls as args[0] to allow "cls" as keyword argument
1295-
cls = args[0]
1296-
args = args[1:]
1297-
1293+
def __new__(cls, /, *args: t.Any, **kwargs: t.Any) -> Self:
12981294
# This is needed because object.__new__ only accepts
12991295
# the cls argument.
13001296
new_meth = super(HasDescriptors, cls).__new__
@@ -1305,13 +1301,10 @@ def __new__(*args: t.Any, **kwargs: t.Any) -> t.Any:
13051301
inst.setup_instance(*args, **kwargs)
13061302
return inst
13071303

1308-
def setup_instance(*args: t.Any, **kwargs: t.Any) -> None:
1304+
def setup_instance(self, /, *args: t.Any, **kwargs: t.Any) -> None:
13091305
"""
13101306
This is called **before** self.__init__ is called.
13111307
"""
1312-
# Pass self as args[0] to allow "self" as keyword argument
1313-
self = args[0]
1314-
args = args[1:]
13151308

13161309
self._cross_validation_lock = False
13171310
cls = self.__class__
@@ -1333,11 +1326,7 @@ class HasTraits(HasDescriptors, metaclass=MetaHasTraits):
13331326
_traits: dict[str, t.Any]
13341327
_all_trait_default_generators: dict[str, t.Any]
13351328

1336-
def setup_instance(*args: t.Any, **kwargs: t.Any) -> None:
1337-
# Pass self as args[0] to allow "self" as keyword argument
1338-
self = args[0]
1339-
args = args[1:]
1340-
1329+
def setup_instance(self, /, *args: t.Any, **kwargs: t.Any) -> None:
13411330
# although we'd prefer to set only the initial values not present
13421331
# in kwargs, we will overwrite them in `__init__`, and simply making
13431332
# a copy of a dict is faster than checking for each key.

0 commit comments

Comments
 (0)