程式扎記: [ Python 常見問題 ] Python list function argument names

標籤

2015年6月24日 星期三

[ Python 常見問題 ] Python list function argument names

Source From Here 
Question 
Is there a way to get the argument names a function takes? For example: 
  1. def foo(bar, buz):  
  2.     pass  
I can use magical_way this way: 
  1. magical_way(foo) == ["bar""buz"]  
How-To 
Use the inspect method from Python's standard library (the cleanest, most solid way to perform introspection). 

inspect.getargspec(f) returns the names and default values of f's arguments: 
Get the names and default values of a Python function’s arguments. A tuple of four things is returned: (args, varargs, keywords, defaults)args is a list of the argument names (it may contain nested lists). varargs and keywords are the names of the * and ** arguments or None. defaults is a tuple of default argument values or None if there are no default arguments; if this tuple has n elements, they correspond to the last n elements listed in args.

A testing example: 
>>> import inspect
>>> def f(a, b='b', c=3, *args, **kwards):
... pass
...
>>> inspect.getargspec(f)
ArgSpec(args=['a', 'b', 'c'], varargs='args', keywords='kwards', defaults=('b', 3))
>>> inspect.getargspec(f)[0] # If you are only interested in the defined argument names
['a', 'b', 'c']

If you only want the names and don't care about special forms *a, **k, 
  1. import inspect  
  2.   
  3. ef magical_way(f):  
  4.    return inspect.getargspec(f)[0]  

Supplement 
Getting method parameter names in python 5 answers 
Getting list of parameter names inside python function 4 answers 
Python *args and **kwargs?

沒有留言:

張貼留言

網誌存檔

關於我自己

我的相片
Where there is a will, there is a way!