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

后端 未结 9 2086
暗喜
暗喜 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)
    

提交回复
热议问题