Function call as default function argument

Having

# example.py def foo(arg=bar()): pass 

will execute bar even with from example import foo .

I remember that a long time ago I saw something like:

 # example.py def foo(arg=lambda: bar()): pass 

but I'm not sure if this is the best way, and now that I'm stuck with this, I can’t find any information on how to deal with this behavior.

What is the correct way to call a function as an argument to a default function in python?

+5
source share
1 answer

This is the most pythonic way:

 def foo(arg=None): if arg is None: arg = bar() ... 

If you want the bar function to be called only once, and you do not want it to be called during import, then you will need to maintain this state somewhere. Perhaps in the called 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() 
+9
source

Source: https://habr.com/ru/post/1270928/


All Articles