Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Allow type checkers to infer trait types #788

Closed
wants to merge 6 commits into from
Closed
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion traitlets/tests/test_typing.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,12 +9,13 @@
@pytest.mark.mypy_testing
def mypy_bool_typing():
class T(HasTraits):
b = Bool()
b = Bool().tag(sync=True)

t = T()
reveal_type(t.b) # R: Union[builtins.bool, None]
# we would expect this to be Optional[Union[bool, int]], but...
t.b = "foo" # E: Incompatible types in assignment (expression has type "str", variable has type "Optional[int]") [assignment]
T.b.tag(foo=True)


@pytest.mark.mypy_testing
Expand Down
4 changes: 3 additions & 1 deletion traitlets/traitlets.py
Original file line number Diff line number Diff line change
Expand Up @@ -518,6 +518,8 @@ def instance_init(self, obj):
G = t.TypeVar("G")
S = t.TypeVar("S")

Self = t.TypeVar("Self", bound="TraitType") # Holdover waiting for typings.Self in Python 3.11


class TraitType(BaseDescriptor, t.Generic[G, S]):
"""A base class for all trait types."""
Expand Down Expand Up @@ -855,7 +857,7 @@ def set_metadata(self, key, value):
warn("Deprecated in traitlets 4.1, " + msg, DeprecationWarning, stacklevel=2)
self.metadata[key] = value

def tag(self, **metadata):
def tag(self, **metadata) -> "TraitType[G, S]":
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think with the typing_extension package we can do this:

Suggested change
def tag(self, **metadata) -> "TraitType[G, S]":
def tag(self, **metadata) -> typing_extension.Self":

"""Sets metadata and returns self.

This allows convenient metadata tagging when initializing the trait, such as:
Expand Down