user380772
user380772

Reputation:

In Python, is there an easier way to make one argument default to another?

In Python 3.3.3, when I try

def f(x,y=0):
 z = x+y
 return z

it works just fine.
However, when I try

def f(x,y=x):
 z = x+y
 return z

I get NameError: name 'x' is not defined.
I am aware that I could just do

def f(x,y=None):
 y = x if y is None else y
 z = x+y
 return z

.


Is there a more concise or otherwise better way to get the desired result?

Upvotes: 0

Views: 87

Answers (4)

dstromberg
dstromberg

Reputation: 7167

Don't fear the simplicity:

def f(x, y=None):
    if y is None:
        y = x
    z = x + y
    return z

You almost certainly should also have a docstring and better identifier names.

"Concision" in Python is frequently pointlessly complex.

Python is a sublime because you can write very clear code with it. Don't try to turn it into something it shouldn't be.

https://stackoverflow.com/questions/1103299/help-me-understand-this-brian-kernighan-quote

Upvotes: 2

martineau
martineau

Reputation: 123393

While not clearly better, here's one way:

def f(x, **kwargs):
    y = kwargs.get('y', x)
    z = x + y
    return z

print f(1)       # -> 2
print f(1, y=2)  # -> 3

Upvotes: -2

Joran Beasley
Joran Beasley

Reputation: 113930

def f(x,y=None):
 z = x + (x if y is None else y)
 return z

is more concise ...

def f(x,y=None):
     return x + (x if y is None else y)

is even more concise

f = lambda x,y=None:x + (x if y is None else y)

is probably as concise as you can make it ...

Upvotes: 0

user2357112
user2357112

Reputation: 280207

No. Default arguments are evaluated at function definition time, and at function definition time, we don't have an x yet. Explicitly checking for a sentinel value is the best we can do.

Upvotes: 7

Related Questions