I would like to simply access the type annotations that I've declared in my class definition's __init__
method:
class Cls:
def __init__(self, data: dict)
pass
def get_type(function):
# What goes here?
cls = Cls({})
get_type(cls.__init__) # Returns 'dict' type.
import inspect
def get_type(function):
print(inspect.formatargspec(*inspect.getfullargspec(function)))
will print (self, data: dict)
.
Use the inspect
modules getmembers
function: https://docs.python.org/3/library/inspect.html
It returns a list of members for whatever object you pass. If you pass a function, it will include a two-tuple where the first element is '__annotations__'
and the second element is a dictionary that maps the parameter name to type annotation. Currently (Python 3.7) the getmembers
function will return the '__annotations__'
tuple as the first element, so the following will work:
import inspect
class Cls:
def __init__(self, data: dict)
pass
def get_type(function, param_name):
return inspect.getmembers(function)[0][1][param_name]
cls = Cls({})
get_type(cls.__init__, 'data') # Returns dict
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.