Expressing type hint of sibling nested class in class constructor

Viewed 318

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"?

1 Answers

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.

Related