Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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)

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading