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?

沒有留言:

張貼留言

[Git 常見問題] error: The following untracked working tree files would be overwritten by merge

  Source From  Here 方案1: // x -----删除忽略文件已经对 git 来说不识别的文件 // d -----删除未被添加到 git 的路径中的文件 // f -----强制运行 #   git clean -d -fx 方案2: 今天在服务器上  gi...