Consider a nested class which defines the type of an outer class attribute:
class Test():
def __init__(self):
self.foo: list[self.Test2] = []
class Test2():
pass
Using various type checkers this annotation is invalid. For example, PyRight takes the type of the assigned value, which is the generic list []
and not on the type hint list[self.Test2]
.
(variable) foo: list
If I assign a variable at the outermost scope with bar: list[Test.Test2] = []
, it works correctly:
(variable) bar: list[Test2]
How do I make foo
take list[Test2]
as its type?
The underlying issue is that self
is not a type, and as such self.Test2
is not either.
Use a static reference to the type and it will work.
class Test:
def __init__(self):
self.foo: list[Test.Test2] = []
class Test2:
pass
If name length is a concern, use an alias.
class Test:
def __init__(self):
self.foo: list[T2] = []
class Test2:
pass
T2 = Test.Test2
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.