Sorry for questioning here... If there is a better place will be grateful for pointing to :)
I'm looking for code-saving algorithm of construction generics. And, explored typing module a bit, came to the solution, workes for me:
import typing as ty
T = ty.TypeVar('T')
class A(ty.Generic[T]):
# __args are unique every instantiation
__args: ty.Optional[ty.Tuple[ty.Type[T]]] = None
value: T
def __init__(self, value: ty.Optional[T]=None) -> None:
"""Get actual type of generic and initizalize it's value."""
cls = ty.cast(A, self.__class__)
if cls.__args:
self.ref = cls.__args[0]
else:
self.ref = type(value)
if value:
self.value = value
else:
self.value = self.ref()
cls.__args = None
def __class_getitem__(cls, *args: type) -> ty.Type['A']:
"""Recive type args, if passed any before initialization."""
cls.__args = ty.cast(ty.Tuple[ty.Type[T]], args)
return super().__class_getitem__(*args, **kwargs) # type: ignore
a = A[int]()
b = A(int())
c = A[str]()
print([a.value, b.value, c.value]) # [0, 0, '']
How dangerous to use this internal interpretation of typing public API?
Sorry for questioning here... If there is a better place will be grateful for pointing to :)
I'm looking for code-saving algorithm of construction generics. And, explored typing module a bit, came to the solution, workes for me:
How dangerous to use this internal interpretation of typing public API?