Is it possible, somehow, to aassign a condtional statement toan optional argument?
My initial attempts, using the following construct, have been unsuccessful:
y = {some value} if x == {someValue} else {anotherValue}
where x has assigned beforehand.
More specifically, I want my function signature to look something like:
def x(a, b = 'a' if someModule.someFunction() else someModule.someOtherFunction()):
:
:
Many thanks
解决方案
Sure, that's exactly how you do it. You may want to keep in mind that b's default value will be set immediately after you define the function, which may not be desirable:
def test():
print("I'm called only once")
return False
def foo(b=5 if test() else 10):
print(b)
foo()
foo()
And the output:
I'm called only once
10
10
Just because this is possible doesn't mean that you should do it. I wouldn't, at least. The verbose way with using None as a placeholder is easier to understand:
def foo(b=None):
if b is None:
b = 5 if test() else 10
print b