typing
typing copied to clipboard
Typing decorators which enrich a class
Hi
I would like to type a decorator which takes as input a class and returns the same class with added attributes, i.e., a subclass. Example:
import typing
_T = typing.TypeVar("_T")
def config(*, /, prefix: str) -> typing.Callable[[typing.Type[_T], ???]:
def wrap(cls: typing.Type[_T]) -> ???:
class Subclass(cls): # or could do cls.prefix = prefix instead of subclassing
prefix: str = prefix
return Subclass
return wrap
@config(prefix="test")
class A:
...
print(A.prefix)
Been searching for an answer and experimenting for a few days now and can't find anything concrete. Any help would be much appreciated
Thank you
I think that's currently impossible because of two reasons:
- Type intersections aren't implemented yet (#213),
which you would need to express
Callable[[type[_T]], type[_T] & MyType]. - Types can be final, in which case you cannot subclass them, e.g.
types.NoneTypeis marked as final. There does not appear to be a type for final types (typing.Finalis something different), which you would need to exclude the type with something likeNot[Final]in the TypeVarbound. Note thatNot[T]also isn't implemented yet (#801).