2

Consider this function:

def foo(x, y=1):
  return x*x + y*y

now I want to call foo like this:

if param_y == None:
  z = foo(3)
else:
  z=foo(3,param_y)

Where param_y is determined somewhere before. I want to simplify this, such that there is only one foo-call in the code, especially since if I have multiple of such optional parameters, I'd get an enormous (and ugly!!) if-else clause, so I can do:

z = foo(3, param_y if param_y != None else 1)

But this requires the caller to know that 1 is the default value of y, which I find a bit ugly as well. Is there an alternative syntax for this, like:

z =  foo(3, if param_y != None: param_y)
Herbert
  • 5,279
  • 5
  • 44
  • 69

1 Answers1

2

Can't you update the foo function?

def foo(x, y):
    if y is None:
        y = 1
    return x*x + y*y

and call everytime :

z=foo(3,param_y)
BriceP
  • 508
  • 2
  • 13