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

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

    I am quite convinced that there is no 'pythonic' way to do this, because this is not a pattern that is pythonic. Control should not reach an undefined variable reference in elegant code. There are similar ideas that are pythonic. Most obvious:

    def myRange(start, stop=None):
        start, stop = (0, start) if stop is None else (start, stop)
        ...
    

    What's important is that stop is defined in scope, but the caller didn't have to pass it explicitly, only that it has taken it's default value, altering the semantics of the arguments, which in effect causes the first argument to be optional instead of the second, even where the language does not allow that without this clever trick.

    That being said, something like this might follow the premise without using a try-catch block.

    a = locals().get('x', y)
    
    0 讨论(0)
  • 2021-02-01 05:01

    If it's an argument to a function you can do this:

    def MyFunc( a=2 ):
        print "a is %d"%a
    
    >>> MyFunc()
    ...a is 2
    >>> MyFunc(5)
    ...a is 5
    

    [Edit] For the downvoters.. the if/else bit is unnecessary for the solution - just added to make the results clear. Edited it to remove the if statement if that makes it clearer?

    0 讨论(0)
  • 2021-02-01 05:07

    I think this would help, since the problem comes down to check whether a variable is defined or not:
    Easy way to check that variable is defined in python?

    0 讨论(0)
提交回复
热议问题