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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With