Using Types of Members of Generic Containers #1087
-
I currently have code that uses a generic config like class that is processed by various other classes. Sometimes those other classes there types depend on what types contained by config class. Something like, class Config(Generic[T1, T2]):
foo: dict[str, T1]
bar: list[T1]
baz: T2
# ... (more shared non-generic elements)
ConfigT = TypeVar('ConfigT', bound=Config)
class Processor(Generic[ConfigT]):
def __init__(self, config: ConfigT):
self._config = config
def process_foo(self) -> list[XYZ]:
return list(self._config.foo.values()) The main issue is filling in x = self.process_foo()
x.extend(self._config.bar) is good but x = self.process_foo()
x.append(self._config.baz) is an error. |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
How about this? class Processor(Generic[T1, T2]):
def __init__(self, config: Config[T1, T2]):
self._config = config
def process_foo(self) -> list[T1]:
return list(self._config.foo.values()) |
Beta Was this translation helpful? Give feedback.
How about this?