Of course, this is exactly how you do it. You can keep in mind that the default value b will be set immediately after the function is defined, which may be undesirable:
def test(): print("I'm called only once") return False def foo(b=5 if test() else 10): print(b) foo() foo()
And the conclusion:
I'm called only once 10 10
Just because it is possible does not mean that you should do it. At least I would not do that. The detailed way to use None as a placeholder is easier to understand:
def foo(b=None): if b is None: b = 5 if test() else 10 print b
source share