Get a list/tuple/dict of the arguments passed to a function?

前端 未结 8 1194
梦如初夏
梦如初夏 2020-12-01 13:17

Given the following function:

def foo(a, b, c):
    pass

How would one obtain a list/tuple/dict/etc of the arguments passed in, wit

8条回答
  •  天涯浪人
    2020-12-01 14:01

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

    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:

    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.

提交回复
热议问题