开发者

Python list function argument names [duplicate]

This question already has answers here: How to get method parameter names? (20 answers) Getting list of parameter names inside python function [duplicate] (4 answers) Closed 9 years ago. 开发者_运维知识库

Is there a way to get the parameter names a function takes?

def foo(bar, buz):
    pass

magical_way(foo) == ["bar", "buz"]


Use the inspect module from Python's standard library (the cleanest, most solid way to perform introspection).

Specifically, inspect.getargspec(f) returns the names and default values of f's arguments -- if you only want the names and don't care about special forms *a, **k,

import inspect

def magical_way(f):
    return inspect.getargspec(f)[0]

completely meets your expressed requirements.


>>> import inspect
>>> def foo(bar, buz):
...     pass
... 
>>> inspect.getargspec(foo)
ArgSpec(args=['bar', 'buz'], varargs=None, keywords=None, defaults=None)
>>> def magical_way(func):
...     return inspect.getargspec(func).args
... 
>>> magical_way(foo)
['bar', 'buz']
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜