Kwargs in a function

Question:

I’m new to Python and just learned about **kwargs.

def myfunc(**kwargs):
    if 'fruit' in kwargs:
        print(f'My fruit of choice is {kwargs["fruit"]}')
    else:
        print('I did not find any fruit here')

myfunc(fruit='apple')

When calling the function, why is the keyword fruit not in quotations?

Why is it different from this:

d = {'one':1}

d['one']

Thanks in advance.

Asked By: OGreeni

||

Answers:

The short answer is "that’s just how it works".

The longer answer:

Within the context of a function call, argument names aren’t str objects, or any other kind of object or expression; they’re just names. They don’t have quotes because they aren’t string literal expressions.

In other words, you can’t do:

>>> myfunc('fruit'='apple')
  File "<stdin>", line 1
SyntaxError: expression cannot contain assignment, perhaps you meant "=="?

nor can you do:

>>> argname = 'fruit'
>>> myfunc(argname='apple')  # argname does not evaluate to 'fruit'!
I did not find any fruit here

In your dictionary lookup example, you can use any kind of expression as a dictionary key:

>>> d['o'+'n'+'e']
1
>>> one = 'one'
>>> d[one]
1

so if you want the key to be a string literal, you need to put quotes around it.

The named argument syntax is easier to understand IMO if you actually name the arguments in the function definition instead of using **kwargs to accept arbitrary arguments:

def myfunc(fruit=None):
    if fruit is not None:
        print(f'My fruit of choice is {fruit}')
    else:
        print('I did not find any fruit here')

This way the syntax looks the same in the function definition as it does in the caller (fruit is a name, not the string literal 'fruit').

Note that you can use the ** syntax the other way around, to pass a dictionary of named arguments; in this case the dictionary is defined normally, with str keys that can be string literals or other str expressions:

>>> myfunc(fruit='apple')
My fruit of choice is apple
>>> myfunc(**{'fruit': 'apple'})
My fruit of choice is apple
>>> k = 'fruit'
>>> v = 'apple'
>>> myfunc(**{k: v})
My fruit of choice is apple
Answered By: Samwise
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.