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

后端 未结 9 2180
暗喜
暗喜 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:52

    Since 2.5:

    If you want to fall back only on None:

    a = x if x is not None else y 
    

    If you want to fall back also on empty string, false, 0 etc.:

    a = x if x else y 
    

    or

    a = x or y 
    

    As for undefined (as never defined, a.k.a. not bound):

    try:
      a = x 
    except NameError:
      a = y
    

    or a bit more hackish (I'd not really recommend that, but it's short):

    a = vars().get('x',y)
    

提交回复
热议问题