开发者

Find out the number of arguments passed to a function consisting of default values for arguments in python

Consider the following python 开发者_运维问答function:

def fun(x=0,y=1,z=1):
  print x,y,z

fun(2)

Is there a way i can find out within the function how many arguments were actually passed to it,which in the above case is 1 ?

Please Help Thank You


Have a look at the inspect module

import inspect
inspect.getargspec(someMethod)

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.


>>> def fun(x=0,y=1,z=1):
...   print x,y,z
... 
>>> func = fun
>>> func.func_code.co_argcount
3
>>> func.func_code.co_varnames
('x', 'y', 'z')

You can also try inspect module

>>> import inspect
>>> inspect.getargspec(func).args
['x', 'y', 'z']
>>> inspect.getargspec(func)
ArgSpec(args=['x', 'y', 'z'], varargs=None, keywords=None, defaults=(0, 1, 1))


Are you looking something like:

def fun(**kwargs):
    arg_count = len(kwargs)
    print("Function called with",arg_count,"arguments")
    params = {"x": 0, "y": 1, "z":1} #defaults
    params.update(kwargs)
    print("Now arguments are", params, )

fun(x=2)

Output:

Function called with 1 arguments
Now arguments are {'y': 1, 'x': 2, 'z': 1}
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜