Optional arguments to a Python function - can I add as a condition?

Is it possible to somehow assign a conditional operator to an optional argument?

My initial attempts, using the following construction, were unsuccessful:

y = {some value} if x == {someValue} else {anotherValue} 

where x is assigned in advance.

In particular, I want my function signature to look something like this:

 def x(a, b = 'a' if someModule.someFunction() else someModule.someOtherFunction()): : : 

Thank you very much

+2
source share
1 answer

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 
+7
source

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


All Articles