简体   繁体   中英

Expressing type hint of sibling nested class in class constructor

I am using the type hinting system of python when coding with pycharm, which I believe uses the typing module, however I have a scenario for which pycharm gives me an error and I can not find an answer on how to make it right online:

from typing import List


class Something:
    class A(object):
        def __init__(self, d: int) -> None:
            self.data = d

    class B(object):
        def __init__(self, inListStr: List[str], inListA: List[A]): # "A" here is marked as "Unresolved Reference". Something.A does not fix the issue either
            self.list_of_str = inListStr
            self.list_of_a = inListA

    def __init__(self, inB: B): #B here is accepted ok
        self.data_b = inB

Do you know how I can correctly type inListA to be of type "list of As"?

Use Something.A , but enclose it in quotes:

...
        def __init__(self, inListStr: List[str], inListA: List['Something.A']):
...

The Python interpreter can't evaluate A or Something.A at that point in the code. By making it a string, the type checker can still figure out the type while avoiding runtime evaluation.

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