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

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

    Most of the solutions relying on if statements don't work for the case where x is 0 or negative.

    >>> x = 0
    >>> y = 2
    >>> a = x or y
    >>> a
    2
    >>> 
    

    If you knew the name of the variable ahead of time you could look for like so:

    if 'x' in dir():
        a = x 
    except:
         a =y
    

    However that solution seems kind of sloppy to me. I believe the best method is to use a try except block like so:

    try:
        a = x
    else:
        a = y
    

提交回复
热议问题