Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Function call as a default function argument

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?

like image 922
pythad Avatar asked Aug 16 '17 16:08

pythad


People also ask

Can a function call be an argument?

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.

What can be used as a default function 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.

What is the default function call method?

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.

What are the arguments given in the function call called?

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.


1 Answers

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()
like image 161
wim Avatar answered Oct 18 '22 22:10

wim