Checking for member existence in Python

前端 未结 5 1548
北恋
北恋 2020-12-01 14:23

I regularly want to check if an object has a member or not. An example is the creation of a singleton in a function. For that purpose, you can use hasattr like

5条回答
  •  独厮守ぢ
    2020-12-01 14:49

    It depends on which case is "typical", because exceptions should model, well, atypical conditions. So, if the typical case is that the instance attribute should exist, then use the second code style. If not having instance is as typical as having instance, then use the first style.

    In the specific case of creating a singleton, I'm inclined to go with the first style, because creating a singleton the initial time is a typical use case. :-)

提交回复
热议问题