What's the pythonic way of conditional variable initialization?

前端 未结 5 1773
名媛妹妹
名媛妹妹 2021-02-07 16:51

Due to the scoping rules of Python, all variables once initialized within a scope are available thereafter. Since conditionals do not introduce new scope, constructs in other l

相关标签:
5条回答
  • 2021-02-07 17:02

    Python also has a very useful if syntax pattern which you can use here

      message = get_other_message() if optional_var else get_message()
    

    Or if you want to compare strictly with None

      message = get_other_message() if optional_var is not None else get_message()
    

    Unlike with example 1) you posted this doesn't call get_message() unnecessarily.

    0 讨论(0)
  • 2021-02-07 17:08

    In general second approach is better and more generic because it doesn't involve calling get_message unconditionally. Which may be ok if that function is not resource incentive but consider a search function

    def search(engine):
        results = get_from_google()
        if engine == 'bing':
           results = get_from_bing()
    

    obviously this is not good, i can't think of such bad scenario for second case, so basically a approach which goes thru all options and finally does the default is best e.g.

    def search(engine):
        if engine == 'bing':
           results = get_from_bing()
        else:
           results = get_from_google()
    
    0 讨论(0)
  • 2021-02-07 17:14

    I think it's more pythonic to not set an explicit rule about this, and instead just keep to the idea that smallish functions are better (in part because it's possible to keep in your mind just when new names are introduced).

    I suppose though that if your conditional tests get much more complicated than an if/else you may run the risk of all of them failing and you later using an undefined name, resulting in a possible runtime error, unless you are very careful. That might be an argument for the first style, when it's possible.

    0 讨论(0)
  • 2021-02-07 17:18

    The answer depends on if there are side effects of get_message() which are wanted.

    In most cases clearly the second one wins, because the code which produces the unwanted result is not executed. But if you need the side effects, you should choose the first version.

    0 讨论(0)
  • 2021-02-07 17:18

    It might be better (read: safer) to initialize your variable outside the conditions. If you have to define other conditions or even remove some, the user of message later on might get an uninitialized variable exception.

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