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

How do I indicate that a Generic container can be heterogeneous?

Say I want to create a custom class and make use of contained type hinting like in list[int]. As I understand I would do that like:

from typing import Generic, TypeVar

T = TypeVar("T")

class MyContainer(Generic[T]):
    def __init__(self, ls: list[T]):
        pass

    def __getitem__(self, ix: int) -> T:
        pass

But does this now imply it’s a homogeneous container? Do I have to do anything special to use it like (c = MyContainer(['a', 1]))?

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 :

c = MyContainer(['a', 1]) doesn’t make any actual use of Generics (type is defaulted to Any). You need to pass type parameter for MyContainer, to tell what is the actual type variable to be used in place of T. For example:

c = MyContainer[str](['a', 1])

This will obviously trigger type checker to issue a warning:

Argument of type "list[str | int]" cannot be assigned to parameter "ls" of type "list[str]" in function "__init__"
  "Literal[1]" is incompatible with "str"

So, now it’s a matter of correctly telling your class what you actually want to have in place of a type generic.
If you want to accept strings and ints but nothing else, typing it as:

c = MyContainer[str | int](['a', 1])

will work just fine.

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