Search code examples
pythonmypypython-typing

Why do I need a generic only when the constructor has a parameter


from typing import TypeVar

T = TypeVar('T')

class MyList:
    def __init__(self):
        self.my_list: list[T] = []

class MyListWithX:
    def __init__(self, x: int):
        self.my_list: list[T] = []

The first class works fine, the second class throws the following error

main.py:11: error: Type variable "main.T" is unbound                                                   
main.py:11: note: (Hint: Use "Generic[T]" or "Protocol[T]" base class to bind "T" inside a class)  
main.py:11: note: (Hint: Use "T" in function signature to bind "T" inside a function) 

It tells what how to fix it, that is not the question, my question is

why do I need to use Generic only if my constructor has a parameter(self excluded)


Solution

  • It's not that your constructor has a parameter, it's that it has a type annotation (which happens to be on your parameter). By default, typechecking is only enabled on functions that have type annotations in their definition. If you do:

    from typing import TypeVar
    
    T = TypeVar('T')
    
    class MyList:
        def __init__(self) -> None:
            self.my_list: list[T] = []
    

    you will see the error.