What's the pythonic way of conditional variable initialization?

前端 未结 5 1030
情书的邮戳
情书的邮戳 2021-02-07 16:56

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 16:59

    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.

提交回复
热议问题