What's the pythonic way of conditional variable initialization?

前端 未结 5 1029
情书的邮戳
情书的邮戳 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 17:13

    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.

提交回复
热议问题