How to get method parameter names?

前端 未结 15 2134
眼角桃花
眼角桃花 2020-11-22 09:14

Given the Python function:

def a_method(arg1, arg2):
    pass

How can I extract the number and names of the arguments. I.e., given that I h

15条回答
  •  孤街浪徒
    2020-11-22 09:49

    In Python 3.+ with the Signature object at hand, an easy way to get a mapping between argument names to values, is using the Signature's bind() method!

    For example, here is a decorator for printing a map like that:

    import inspect
    
    def decorator(f):
        def wrapper(*args, **kwargs):
            bound_args = inspect.signature(f).bind(*args, **kwargs)
            bound_args.apply_defaults()
            print(dict(bound_args.arguments))
    
            return f(*args, **kwargs)
    
        return wrapper
    
    @decorator
    def foo(x, y, param_with_default="bars", **kwargs):
        pass
    
    foo(1, 2, extra="baz")
    # This will print: {'kwargs': {'extra': 'baz'}, 'param_with_default': 'bars', 'y': 2, 'x': 1}
    

提交回复
热议问题