-
I am having trouble narrowing a dataclass field. See the example below. The last line gives the error. How can this be typed correctly? Adding from dataclasses import dataclass
@dataclass
class Info:
data: str | None = None
class Foo:
def __init__(self, info: Info):
if info.data is None:
raise ValueError("Data cannot be None")
self.info = info
def get_data(self) -> str:
return self.info.data #pylance error on this line Pylance Error
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
In your example, the type of Pyright will narrow more complex expressions like 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 def get_data(self) -> str:
assert self.info.data is not None
return self.info.data For more details about type narrowing, refer to this documentation. |
Beta Was this translation helpful? Give feedback.
In your example, the type of
info
isInfo
. There's no narrower type thanInfo
, 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:
If you want to narrow
self.info.data
within theget_data
method, you'd need to add some logic to that method. For example, anassert
statement will document your assumptions for both human readers and a typ…