【问题标题】:Getting list of parameter names inside python function [duplicate]获取python函数中的参数名称列表[重复]
【发布时间】:2010-10-09 14:01:33
【问题描述】:

可能重复:
Getting method parameter names in python

有没有一种简单的方法可以进入 python 函数并获取参数名称列表?

例如:

def func(a,b,c):
    print magic_that_does_what_I_want()

>>> func()
['a','b','c']

谢谢

【问题讨论】:

    标签: python parameters


    【解决方案1】:

    locals() 返回带有本地名称的字典:

    def func(a,b,c):
        print(locals().keys())
    

    打印参数列表。如果您使用其他局部变量,这些变量将包含在此列表中。但您可以在函数开始时复制一份。

    【讨论】:

    • print locals().keys() 将返回 ['arg']。我用print locals.get('arg')
    • 谢谢!我对"found {thing} in {place}, took {action}, resulting in {result}".format(**locals()) 有了新的爱,而不是"found {thing} in {place}, took {action}, resulting in {result}".format(thing=thing, place=place, action=action, result=result)
    • 小心,locals() 也返回命名空间变量,例如def func(a,b,c): d=4; print(locals()['d'])
    • @BrunoBronosky 为什么不直接使用 f-strings? f'found {thing} in {place}, took {action}, resulting in {result}'
    • @speedstyle f-strings 是在 Python 3.6 中引入的。评论来自3.5。 (是的,f-strings 更好:D)
    【解决方案2】:
    import inspect
    
    def func(a,b,c=5):
        pass
    
    inspect.getargspec(func)  # inspect.signature(func) in Python 3
    
    (['a', 'b', 'c'], None, None, (5,))
    

    【讨论】:

    • 这不在函数内部..
    • 你也可以在函数里面做
    • 这实际上更好,因为它显示了如何获取不是您自己编写的方法的参数。
    • 在 Python 3 中使用 inspect.signature
    • @DavidC 更新链接inspect.signature
    【解决方案3】:

    如果您还想要这些值,可以使用 inspect 模块

    import inspect
    
    def func(a, b, c):
        frame = inspect.currentframe()
        args, _, _, values = inspect.getargvalues(frame)
        print 'function name "%s"' % inspect.getframeinfo(frame)[2]
        for i in args:
            print "    %s = %s" % (i, values[i])
        return [(i, values[i]) for i in args]
    
    >>> func(1, 2, 3)
    function name "func"
        a = 1
        b = 2
        c = 3
    [('a', 1), ('b', 2), ('c', 3)]
    

    【讨论】:

    • Kelly Yancey's blog 有一篇很棒的帖子详细解释了这一点,并给出了一个稍微更精致的版本,并与例如未知的解决方案。推荐。
    • def foo(first, second, third, *therest): 呢?
    【解决方案4】:

    我们实际上并不需要inspect

    >>> func = lambda x, y: (x, y)
    >>> 
    >>> func.__code__.co_argcount
    2
    >>> func.__code__.co_varnames
    ('x', 'y')
    >>>
    >>> def func2(x,y=3):
    ...  print(func2.__code__.co_varnames)
    ...  pass # Other things
    ... 
    >>> func2(3,3)
    ('x', 'y')
    >>> 
    >>> func2.__defaults__
    (3,)
    

    对于 Python 2.5 及更早版本,使用 func_code 代替 __code__,使用 func_defaults 代替 __defaults__

    【讨论】:

    • 应该是 func.func_code.co_varnames[:func.func_code.co_argcount],因为 co_varnames 是函数中存在的所有变量的元组
    • 在 python3 中这将是 func.__code__.co_varnames
    • 这只适用于非'builtin_function_or_method'。
    • 我使用 Python 2.7.8,而 __code__ 似乎被向后移植了。 func_code 也仍然有效。
    • 请使用检查。否则,您的代码在 3.4+ 中无法与 functools.wraps 一起使用。见stackoverflow.com/questions/147816/…
    猜你喜欢
    • 2011-03-31
    • 2022-01-12
    • 1970-01-01
    • 2021-02-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多