What's the pythonic way of conditional variable initialization?

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

提交回复
热议问题