-1

The following code works correctly:

def myfunc(**kwargs):
if 'fruit' in kwargs:
    print('my fruit of choice is {}'.format(kwargs['fruit']))
else:
    print('No Fruit Here')
myfunc(fruit = 'apple', veggie = 'lettuce)

The following code returns an error:

def myfunc(**kwargs):
if 'fruit' in kwargs:
    print(f'my fruit of choice is {fruit}')
else:
    print('No Fruit Here')
myfunc(fruit = 'apple', veggie = 'lettuce)

Returns: NameError: name 'fruit' is not defined

How would I format it correctly? And also, why isn't it working the way I am trying? Is it because of **kwargs?

Thank you for any help and explaining.

JWingert
  • 111
  • 1
  • 8
  • The name `fruit` does not exist in either case. It's a string key of `kwargs`. If `kwargs['fruit']` worked in the first case, why not try `print(f'my fruit of choice is {kwargs["fruit"]}')`? – r.ook May 13 '20 at 03:00

2 Answers2

1

Close, it should be kwargs['fruit'] because kwargs is a dict containing all the function's parameters

def myfunc(**kwargs):
    print(kwargs)
    if 'fruit' in kwargs:
        print(f"my fruit of choice is {kwargs['fruit']}")
    else:
        print('No Fruit Here')
myfunc(fruit = 'apple', veggie = 'lettuce')
#{'fruit': 'apple', 'veggie': 'lettuce'}
#my fruit of choice is apple
ExplodingGayFish
  • 2,807
  • 1
  • 5
  • 14
0

The problem is that the two cases are not equivalent. In the first case:

print('my fruit of choice is {}'.format(kwargs['fruit']))

You are referring to the object kwargs['fruit'], which exists. This would translate to an f-string of:

print(f'my fruit of choice is {kwargs["fruit"]}')

In your second case, the f-string is equivalent to:

print('my fruit of choice is {}'.format(fruit))

Which would give you the same error, because the object named fruit does not exist.

This is because your function uses variable amount of kwargs, which essentially create a dict named kwargs for your function to refer to locally. If however you had created your function as:

def myfunc(fruit=None, veggie=None, **kwargs):

Then the names fruit and veggie would be known to your function locally, in addition to undefined keyword arguments in the kwargs dict.

r.ook
  • 13,466
  • 2
  • 22
  • 39