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

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

    One way to rewrite...

    if x is not None
        a = x
    else
        a = y
    

    ..is:

    x = myfunction()
    
    if x is None:
        x = y
    
    print x
    

    Or, using exceptions (possibly more Python'y, depending on the what the code is doing - if it returns None because there was an error, using an exception is probably the correct way):

    try:
        x = myfunction()
    except AnException:
        x = "fallback"
    
    print x
    

    All that said, there really isn't anything wrong with you original code:

    if x is not None
        a = x
    else
        a = y
    

    It's long, but I find that far easier to read (and much more Pythonic) than either of the following one-liners:

    a = x if x is not None else y
    a = x or y
    

提交回复
热议问题