Generic class method on non-generic class

Your code almost works. You can fix it by passing the type int as an argument to the CreateItem function:

from dataclasses import dataclass
from typing import TypeVar, Generic

T = TypeVar('T')

@dataclass
class Item(Generic[T]):
    name: str
    value: T = None

class OtherClass:
    def CreateItem(self, tp, name: str, value=None):
        return Item[tp](name=name, value=value)

other = OtherClass()
item = other.CreateItem(int, "some_field", 45)

However, note that type hints in Python are mostly used for static analysis in type checkers like mypy and IDEs. They are usually not used at runtime.

You could also replace OtherClass by this, without using the specific type hint of Item:

class OtherClass2:
    def CreateItem(self, name: str, value=None):
        return Item(name=name, value=value)

other2 = OtherClass2()
item2 = other2.CreateItem("some_field", 45)

There will be no difference between item and item2:

assert item == item2  # this assertion will pass

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top