Jackpy
Jackpy

Reputation: 111

Running a function with a non-existing optional argument

I have create a function which has an optional argument y on it:

def f(x, *y):
    print(x)
    if y in locals():
    print(y)

When passing these x and yarguments to the function it only ouputs x even though y is in the local variables:

a = ['String', 'Optional String']
x = a[0]
if len(a) == 2:
    y = a[1]

f(x, *y) #Output: String

I have a second issue that when giving only the x argument and not the y it ouputs a NameError:

a = ['String', 'Optional String']
x = a[0]
if len(a) == 2:
    y = a[1]

f(x, *y) #Output: NameError: name 'y' is not defined

How can I get this working? Thanks in advance.

EDIT:

Looks like I misunderstood what an optional argument was. Ended up changing the whole code and its Fixed. These answers helped me anyways, Thank you.

Upvotes: 1

Views: 59

Answers (2)

Reinstate Monica
Reinstate Monica

Reputation: 4723

The correct way to check if y is a local name would be if 'y' in locals():.

However, that would always be true, because y is always a local name, even if f is called with only one argument. In which case we have y == (), i.e. y is an empty tuple.

You can simply write if y: if you want to know if there was more than one argument.

def f(x, *y):
    print(x)
    if y:
        print(y)

I can't confirm your second problem. While it doesn't do what you probably want, there is no NameError. (You probably want to drop the asterisk.)

Oh, and if you want optional arguments, use optional arguments. Not variable length arguments.

Upvotes: 2

Gasvom
Gasvom

Reputation: 651

The output of locals is a dictionary - in your function if you were to do:

def f(x, *y):
    print(locals())

f('string', 'other string')

The output would be

{'y': ('other string',), 'x': 'string'}

So to access the values within y, you would call it like so:

def f(x, *y):
    print(x)
    if 'y' in locals():
        print(y)
f('string', 'other string')

Output:

string
other string

Upvotes: 1

Related Questions