pythonpython-3.xcallstackkeyword-argumentcode-inspection

inspect.getargvalues returns keyword only args as args instead of varargs


How can it be explained that inspect.getargvalues returns keyword only args as args instead of varargs. Is this a bug or a documentation bug? Are keyword only args not keyword args? I don't understand.

inspect.getargvalues(frame)

Get information about arguments passed into a particular frame. A named tuple ArgInfo(args, varargs, keywords, locals) is returned. args is a list of the argument names. varargs and keywords are the names of the * and ** arguments or None. locals is the locals dictionary of the given frame.

import inspect
def fun(x, *, y):
    print (inspect.getargvalues(inspect.currentframe()))

Output:

fun (10, y=20)
ArgInfo(args=['x', 'y'], varargs=None, keywords=None, locals={'y': 20, 'x': 10})

Solution

  • As it says: "varargs and keywords are the names of the * and ** arguments". Your function doesn't have any * or ** arguments.

    The * that appears here:

    def fun(x, *, y):
    

    merely serves as a separator between positional arguments and keyword-only arguments.

    This would be an example of a function where varargs and keywords would be set:

    def fun(*x, **y):
        print(inspect.getargvalues(inspect.currentframe()))
    

    which would produce:

    >>> fun(10, y=20)
    ArgInfo(args=[], varargs='x', keywords='y', locals={'x': (10,), 'y': {'y': 20}})