Home > front end >  How to annotate function that returns its argument
How to annotate function that returns its argument

Time:05-16

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)

CodePudding user response:

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
  • Related