Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to annotate function that returns its argument

I’m trying to write decorator that takes additionalparameter like this

def dec(arg):
    def modifier(cls) -> cls:
        # modify cls
        return cls;
    pass
    return modifier
pass
@dec(63)
class X:
    a: int = 47;
pass

This is, of course, error, since cls is not defined.
I’ve tried dec(arg: int) -> Callable[[type], type] and modifier(cls: type) -> type
but that messes up IntelliSense (vscode) (writing X. no longer offers a)

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Use TypeVar to define a generic type that you can use to annotate your function. Use Type to annotate that the function accepts and returns types/classes of the TypeVar

from typing import TypeVar, Type

T = TypeVar('T')


def dec(arg):
    def modifier(cls: Type[T]) -> Type[T]:
        # modify cls
        return cls
    return modifier


@dec(63)
class X:
    a: int = 47
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading