简体   繁体   中英

type hint in method for a nested class?

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

Apparently assigning it to a variable then using it in the type hint works..?

class Test():
    def __init__(self):
        type_hint = self.Test2
        foo: list[type_hint] = []

    class Test2():
        pass

在此处输入图像描述

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM