Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it ok/pythonic to call another function as an optional argument?

Tags:

python

For example, I have a function which does something to data, and takes a name as an optional argument. If the name is not supplied, I want to call another argument to create the name. So the alternatives seem to be either

def do_something(data, name=get_name()):
    ...

or

def do_something(data, name=None):
    if name is None: 
        name=get_name()
    ...

The first one seems better to me, but am I missing something?

like image 587
user6072577 Avatar asked Mar 01 '26 23:03

user6072577


1 Answers

It's not the same thing.

get_name() is evaluated at function definition for the first case, and dynamically for the second case.

There are cases where you cannot use the first method anyway, like when using the return of a method call (self.method())

So stick to the second version. I don't know if it's more pythonic, but at least it is a good recipe and it works.

like image 75
Jean-François Fabre Avatar answered Mar 04 '26 12:03

Jean-François Fabre



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!