What is the most Pythonic way to provide a fall-back value in an assignment?

后端 未结 9 2089
暗喜
暗喜 2021-02-01 04:29

In Perl, it\'s often nice to be able to assign an object, but specify some fall-back value if the variable being assigned from is \'undef\'. For instance:

my $x         


        
9条回答
  •  故里飘歌
    2021-02-01 04:44

    first you can do your full-on with a ternary:

    a = y if x is None else x
    

    but it doesn't solve your problem. what you want to do is more closely implemented with:

    try:
        a = x
    except:
        a = y
    

提交回复
热议问题