Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass an empty parameter to a python function?

Here is the working code:

def g(y=10):
    return y**2

def f(x,y=10):
    return x*g(y)

print(f(5)) #->500

However, let's suppose we don't want to remember and copy a default value of keyword parameter y to the definition of external function (especially if there are several layers of external functions). In the above example it means that we want to use parameter, already defined in g.

One way to do that:

def f(x,y=None):
    if y==None: return x*g()
    else: return x*g(y)

But is there a cleaner way to do the same? Something like:

def f(x,y=empty()):
    return x*g(y)
like image 362
Nik Avatar asked Apr 15 '16 14:04

Nik


1 Answers

Interesting question! Here's another possibility, however this requires handing in the second parameter as a named parameter.

>>> def g(y=10):
...     return y**2
... 
>>> def f(x, **kwargs):
...     return x * g(**kwargs)
... 
>>> f(5)
500
>>> f(5, y=0)
0
like image 184
dorian Avatar answered Sep 24 '22 13:09

dorian