获取传递给函数的参数的列表/元组/字典?

时间:2021-08-16 23:22:12

Given the following function:

鉴于以下功能:

def foo(a, b, c):
    pass

How would one obtain a list/tuple/dict/etc of the arguments passed in, without having to build the structure myself?

如何获得传入的参数的list / tuple / dict / etc,而不必自己构建结构?

Specifically, I'm looking for Python's version of JavaScript's arguments keyword or PHP's func_get_args() method.

具体来说,我正在寻找Python的JavaScript参数关键字版本或PHP的func_get_args()方法。

What I'm not looking for is a solution using *args or **kwargs; I need to specify the argument names in the function definition (to ensure they're being passed in) but within the function I want to work with them in a list- or dict-style structure.

我不想要的是使用* args或** kwargs的解决方案;我需要在函数定义中指定参数名称(以确保它们被传入),但在函数中我希望在list-或dict-style结构中使用它们。

7 个解决方案

#1


63  

You can use locals() to get a dict of the local variables in your function, like this:

您可以使用locals()来获取函数中局部变量的dict,如下所示:

def foo(a, b, c):
    print locals()

>>> foo(1, 2, 3)
{'a': 1, 'c': 3, 'b': 2}

This is a bit hackish, however, as locals() returns all variables in the local scope, not only the arguments passed to the function, so if you don't call it at the very top of the function the result might contain more information than you want:

但是,这有点hackish,因为locals()返回本地范围内的所有变量,而不仅仅是传递给函数的参数,所以如果你不在函数的最顶层调用它,结果可能包含更多信息比你想要的:

def foo(a, b, c):
    x = 4
    y = 5
    print locals()

>>> foo(1, 2, 3)
{'y': 5, 'x': 4, 'c': 3, 'b': 2, 'a': 1}

I would rather construct a dict or list of the variables you need at the top of your function, as suggested in the other answers. It's more explicit and communicates the intent of your code in a more clear way, IMHO.

我希望在函数顶部构建一个dict或变量列表,如其他答案所示。它更明确,并以更清晰的方式传达代码的意图,恕我直言。

#2


7  

You can use the inspect module:

您可以使用inspect模块:

def foo(x):
    return x

inspect.getargspec(foo)
Out[23]: ArgSpec(args=['x'], varargs=None, keywords=None, defaults=None)

This is a duplicate of this and this.

这与此相关。

#3


3  

I would use *args or **kwargs and throw an exception if the arguments are not as expected

如果参数不符合预期,我会使用* args或** kwargs并抛出异常

If you want to have the same errors than the ones checked by python you can do something like

如果你想拥有与python检查的错误相同的错误,你可以做类似的事情

def check_arguments(function_name,args,arg_names):
    missing_count = len(arg_names) - len(args)
    if missing_count > 0:
        if missing_count == 1:
            raise TypeError(function_name+"() missing 1 required positionnal argument: "+repr(arg_names[-1]))
        else:
            raise TypeError(function_name+"() missing "+str(missing_count)+" required positionnal argument: "+", ".join([repr(name) for name in arg_names][-missing_count:-1])+ " and "+repr(arg_names[-1]))

using with somethin like

与某些人一起使用

def f(*args):
    check_arguments("f",args,["a","b","c"])
    #whatever you want
    ...

#4


2  

You've specified the parameters in the header?

你在标题中指定了参数?

Why don't you simply use that same info in the body?

为什么不简单地在身体中使用相同的信息?

def foo(a, b, c):
   params = [a, b, c]

What have I missed?

我错过了什么?

#5


1  

You can create a list out of them using:

您可以使用以下方法创建列表:

args = [a, b, c]

You can easily create a tuple out of them using:

您可以使用以下方法轻松创建元组:

args = (a, b, c)

#6


1  

One solution, using decorators, is here.

这里有一个使用装饰器的解决方案。

#7


0  

From the accepted answer from a duplicate (older??) question https://*.com/a/582206/1136458 :

从一个重复的(旧的??)问题接受答案https://*.com/a/582206/1136458:

    frame = inspect.currentframe()
    args, _, _, values = inspect.getargvalues(frame)

#1


63  

You can use locals() to get a dict of the local variables in your function, like this:

您可以使用locals()来获取函数中局部变量的dict,如下所示:

def foo(a, b, c):
    print locals()

>>> foo(1, 2, 3)
{'a': 1, 'c': 3, 'b': 2}

This is a bit hackish, however, as locals() returns all variables in the local scope, not only the arguments passed to the function, so if you don't call it at the very top of the function the result might contain more information than you want:

但是,这有点hackish,因为locals()返回本地范围内的所有变量,而不仅仅是传递给函数的参数,所以如果你不在函数的最顶层调用它,结果可能包含更多信息比你想要的:

def foo(a, b, c):
    x = 4
    y = 5
    print locals()

>>> foo(1, 2, 3)
{'y': 5, 'x': 4, 'c': 3, 'b': 2, 'a': 1}

I would rather construct a dict or list of the variables you need at the top of your function, as suggested in the other answers. It's more explicit and communicates the intent of your code in a more clear way, IMHO.

我希望在函数顶部构建一个dict或变量列表,如其他答案所示。它更明确,并以更清晰的方式传达代码的意图,恕我直言。

#2


7  

You can use the inspect module:

您可以使用inspect模块:

def foo(x):
    return x

inspect.getargspec(foo)
Out[23]: ArgSpec(args=['x'], varargs=None, keywords=None, defaults=None)

This is a duplicate of this and this.

这与此相关。

#3


3  

I would use *args or **kwargs and throw an exception if the arguments are not as expected

如果参数不符合预期,我会使用* args或** kwargs并抛出异常

If you want to have the same errors than the ones checked by python you can do something like

如果你想拥有与python检查的错误相同的错误,你可以做类似的事情

def check_arguments(function_name,args,arg_names):
    missing_count = len(arg_names) - len(args)
    if missing_count > 0:
        if missing_count == 1:
            raise TypeError(function_name+"() missing 1 required positionnal argument: "+repr(arg_names[-1]))
        else:
            raise TypeError(function_name+"() missing "+str(missing_count)+" required positionnal argument: "+", ".join([repr(name) for name in arg_names][-missing_count:-1])+ " and "+repr(arg_names[-1]))

using with somethin like

与某些人一起使用

def f(*args):
    check_arguments("f",args,["a","b","c"])
    #whatever you want
    ...

#4


2  

You've specified the parameters in the header?

你在标题中指定了参数?

Why don't you simply use that same info in the body?

为什么不简单地在身体中使用相同的信息?

def foo(a, b, c):
   params = [a, b, c]

What have I missed?

我错过了什么?

#5


1  

You can create a list out of them using:

您可以使用以下方法创建列表:

args = [a, b, c]

You can easily create a tuple out of them using:

您可以使用以下方法轻松创建元组:

args = (a, b, c)

#6


1  

One solution, using decorators, is here.

这里有一个使用装饰器的解决方案。

#7


0  

From the accepted answer from a duplicate (older??) question https://*.com/a/582206/1136458 :

从一个重复的(旧的??)问题接受答案https://*.com/a/582206/1136458:

    frame = inspect.currentframe()
    args, _, _, values = inspect.getargvalues(frame)