Python function optional arguments - possible to add as condition?

血红的双手。 提交于 2019-12-23 17:12:15

问题


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


回答1:


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


来源:https://stackoverflow.com/questions/17742177/python-function-optional-arguments-possible-to-add-as-condition

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!