'Python Generics: Call method of generic type
I am creating a generic type Translation which contains a list of TextSegments.
Inside the generic Translation I would like to access one of the generic type's methods (TextSegment.example()). TextSegmentType.example() throws the following:
AttributeError: 'TypeVar' object has no attribute 'example'
How can I access the example method?
Minimal example:
from __future__ import annotations
from abc import ABC, abstractmethod
from typing import TypeVar, Generic, List
class TextSegment(ABC):
@staticmethod
def example() -> TextSegment:
pass
TextSegmentType = TypeVar("TextSegmentType", bound=TextSegment)
class Translation(Generic[TextSegmentType]):
text_segments: List[TextSegmentType] = [TextSegmentType.example()] # = Field(example=TextSegmentType.example())
instance = Translation[TextSegment](text_segments=[TextSegment()])
In the full implementation there are multiple classes inheriting from TextSegment, each overriding the example method:
class TextSegment(ABC):
# @abstractmethod
@staticmethod
def example() -> TextSegment:
pass
class TextSegmentConcrete1(TextSegment):
@staticmethod
def example() -> TextSegment:
return TextSegmentConcrete1()
class TextSegmentConcrete2(TextSegment):
@staticmethod
def example() -> TextSegment:
return TextSegmentConcrete2()
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
