Having
# example.py
def foo(arg=bar()):
pass
will execute bar
even with from example import foo
.
I remember that long time ago I saw something like:
# example.py
def foo(arg=lambda: bar()):
pass
but I'm not sure if it's the best way and now, when I am stuck with this, I can't find any info on how to deal with this behaviour.
What is the correct way to have function call as a default function argument in python?
Because functions are objects we can pass them as arguments to other functions. Functions that can accept other functions as arguments are also called higher-order functions. In the example below, a function greet is created which takes a function as an argument.
Default arguments are only allowed in the parameter lists of function declarations and lambda-expressions, (since C++11) and are not allowed in the declarations of pointers to functions, references to functions, or in typedef declarations.
By default, C++ uses call by value to pass arguments. In general, this means that code within a function cannot alter the arguments used to call the function and above mentioned example while calling max() function used the same method.
Calling the function involves specifying the function name, followed by the function call operator and any data values the function expects to receive. These values are the arguments for the parameters defined for the function. This process is called passing arguments to the function.
This is the most Pythonic way:
def foo(arg=None):
if arg is None:
arg = bar()
...
If you want the function bar
to be called only once, and you don't want it to be called at import time, then you will have to maintain that state somewhere. Perhaps in a callable class:
class Foo:
def __init__(self):
self.default_arg = None
def __call__(self, arg=None):
if arg is None:
if self.default_arg is None:
self.default_arg = bar()
arg = self.default_arg
...
foo = Foo()
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