Search code examples
pythonfunctionkeyword-argument

kwargs different behavior


Dear pythonist that question is for you! I don't ask to solve my task, just ask for explaining why it happens) I know what is args and kwargs when they using but has been really shoked, when have found one thing. So, please check my example, here we pass arguments to the function

def firstFunc(*args, **kwargs):
    print('args' )
    print(args)
    print('kwargs')
    print(kwargs)
    
firstFunc([1, 2], {'firstFirst': 'firstFirst', 'first' : '123', 'second' : '999'})

And thats the result of it, all that we passed we have in args, but kwargs is empty, first of all why we don't have kwargs as dictionary like that we have passed ?

My second question is, why we can get the dictonary from the second function, if we will set it like this kwargs['second'] = 222, that's my code

def firstFunc(*args, **kwargs):
    print('args' )
    print(*args)
    print('kwargs')
    print(**kwargs)
    kwargs['second'] = 222
    secondFunc([1, 2], **kwargs)


def secondFunc(*args, **kwargs):
    print('args' )
    print(args)
    print('kwargs')
    print(kwargs)



firstFunc([1, 2], {'firstFirst': 'firstFirst', 'first' : '123', 'second' : '999'})

but my second function seing kwargs dictonary, how i set it in the first function

hope I described understandable, I am waiting for u answer, please tell me why it hapens, and why I cannot just pass dictionarie as kwargs! many thanks for u

#python #pythonic #kwargs #args #functions

I expected just mine dictionary in kwargs


Solution

  • You're passing the list and the dictionary as two positional arguments, so those two positional arguments are what shows up in your *args in the function body, and **kwargs is an empty dictionary since no keyword arguments were provided.

    If you want to pass each element of the list as its own positional argument, use the * operator:

    firstFunc(*[1, 2])
    

    If you want to also pass each element of the dictionary as a keyword argument, use the ** operator:

    firstFunc(
        *[1, 2],
        **{'firstFirst': 'firstFirst', 'first' : '123', 'second' : '999'}
    )
    

    This is equivalent to doing:

    firstFunc(
        1,
        2,
        firstFirst='firstFirst',
        first='123',
        second='999'
    )