Skip to content

How to narrow a field in a dataclass in __init__? #9749

Answered by erictraut
mmerlo asked this question in Q&A
Discussion options

You must be logged in to vote

In your example, the type of info is Info. There's no narrower type than Info, so narrowing can't be performed.

Pyright will narrow more complex expressions like self.info.data locally within an execution scope (i.e. a function or method body), but type narrowing of expressions does not extend outside that scope because there's no guarantee that the narrowing still applies.

Consider the following:

f = Foo(Info(data="not None"))

f.info.data = None  # This is legal

f.get_data() # Crash

If you want to narrow self.info.data within the get_data method, you'd need to add some logic to that method. For example, an assert statement will document your assumptions for both human readers and a typ…

Replies: 1 comment 1 reply

Comment options

You must be logged in to vote
1 reply
@mmerlo
Comment options

Answer selected by mmerlo
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
2 participants