Skip to content

Typing decorators which enrich a class #1321

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
lijok opened this issue Dec 25, 2022 · 1 comment
Open

Typing decorators which enrich a class #1321

lijok opened this issue Dec 25, 2022 · 1 comment
Labels
topic: feature Discussions about new features for Python's type annotations

Comments

@lijok
Copy link

lijok commented Dec 25, 2022

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

@lijok lijok added the topic: feature Discussions about new features for Python's type annotations label Dec 25, 2022
@not-my-profile
Copy link

I think that's currently impossible because of two reasons:

  1. Type intersections aren't implemented yet (Introduce an Intersection #213),
    which you would need to express Callable[[type[_T]], type[_T] & MyType].
  2. Types can be final, in which case you cannot subclass them, e.g. types.NoneType is marked as final.
    There does not appear to be a type for final types (typing.Final is something different),
    which you would need to exclude the type with something like Not[Final] in the TypeVar bound. Note that Not[T] also isn't implemented yet (Introduce a Not type #801).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
topic: feature Discussions about new features for Python's type annotations
Projects
None yet
Development

No branches or pull requests

2 participants