Typing a delayed initialised variable #1735
Unanswered
alexisdrakopoulos
asked this question in
Q&A
Replies: 1 comment
-
You can simply delete the For example: class Foo:
var: str
def __init__(self) -> None:
pass
def set_up_stuff(self) -> None:
self.var = "hello"
f = Foo()
f.set_up_stuff()
reveal_type(f.var) # Revealed type is "builtins.str" Note that you lose some type safety this way (but based on your question, it looks like you want this). This will pass the type check, but fail when you run the code, because the attribute does not exist yet: f = Foo()
print(f.var) # AttributeError: 'Foo' object has no attribute 'var' |
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
I have lots of variables in
__init__
that currently are not typing compliant as they do something like:self.var: T = None
where
T
can be any number of types likestr
,int
or complex types.I could wrap it with
Optional[]
but it's notOptional
, it's just not initialised yet.I've looked into using Sentinel objects or other features but none seem to really work in an elegant manner. I could also just leave them purely as annotations like
self.var: T,
but this causes uglyAttributeError
s and introduces more issues.I've seen discussions such as:
But none have any relevant solutions for modern Python versions (3.10 onwards) with mypy (or other) support.
What is the "recommended" way to type hint these types of variables?
Beta Was this translation helpful? Give feedback.
All reactions