What's the pythonic way of conditional variable initialization?

前端 未结 5 1774
名媛妹妹
名媛妹妹 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.

提交回复
热议问题