How to iterate over function arguments

后端 未结 5 726
清歌不尽
清歌不尽 2020-12-29 01:40

I have a Python function accepting several string arguments def foo(a, b, c): and concatenating them in a string. I want to iterate over all function arguments

5条回答
  •  攒了一身酷
    2020-12-29 02:38

    You can use the inspect module and define a function like that:

    import inspect
    def f(a,b,c):
        argspec=inspect.getargvalues(inspect.currentframe())
        return argspec
    f(1,2,3)
    ArgInfo(args=['a', 'b', 'c'], varargs=None, keywords=None, locals={'a': 1, 'c': 3, 'b': 2})
    

    in argspec there are all the info you need to perform any operation with argument passed.

    To concatenate the string is sufficient to use the arg info received:

    def f(a,b,c):
        argspec=inspect.getargvalues(inspect.currentframe())
        return ''.join(argspec.locals[arg] for arg in argspec.args)
    

    For reference: http://docs.python.org/library/inspect.html#inspect.getargvalues

提交回复
热议问题