l0b0
l0b0

Reputation: 58908

How to get argument type hint in decorator?

How can I do the following:

import typing

def needs_parameter_type(decorated):
    def decorator(*args):
        [do something with the *type* of bar (aka args[0]), some_class]
        decorated(*args)
    return decorator

@needs_parameter_type
def foo(bar: SomeClass):
    …

foo(…)

The use case is to avoid the following repetition:

@needs_parameter_type(SomeClass)
def foo(bar: SomeClass):
    …

Upvotes: 1

Views: 1224

Answers (1)

Taku
Taku

Reputation: 33744

These are stored in the __annotations__ property of the function, you can access them by this:

def needs_parameter_type(decorated):
    def decorator(*args):
        print(decorated.__annotations__)
        decorated(*args)
    return decorator

@needs_parameter_type
def foo(bar: int):
   pass

foo(1)
#  {"bar": <class "int">}

Upvotes: 4

Related Questions