Sujet : Re: Any way to "subclass" typing.Annotated?
De : ram (at) *nospam* zedat.fu-berlin.de (Stefan Ram)
Groupes : comp.lang.pythonDate : 29. Jan 2025, 14:45:30
Autres entêtes
Organisation : Stefan Ram
Message-ID : <SSCCE-20250129144451@ram.dialup.fu-berlin.de>
References : 1 2
ram@zedat.fu-berlin.de (Stefan Ram) wrote or quoted:
# The factory function
def AbstractClassVariable(type_: T) -> Any:
return Annotated[type_, abstract]
Alright, so now I've got something here that actually compiles!
Python
from typing import Annotated, TypeVar, Any, Generic
# This is your "abstract" flag. It's just a unique object.
abstract = object()
# A generic type variable to keep things flexible.
T = TypeVar("T")
# Define AbstractClassVariable as a class instead of a function
class AbstractClassVariable(Generic[T]):
def __class_getitem__(cls, item):
return Annotated[item, abstract]
class AbstractType(type):
def __new__(cls, name, bases, namespace):
for key, value in namespace.items():
if isinstance(value, type(Annotated)):
if abstract in value.__metadata__:
raise TypeError(f"Abstract class variable '{key}' must be defined")
return super().__new__(cls, name, bases, namespace)
class Foo(object, metaclass=AbstractType):
acv: AbstractClassVariable[int]