Checking for member existence in Python

前端 未结 5 1581
北恋
北恋 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:34

    These are two different methodologies: №1 is LBYL (look before you leap) and №2 is EAFP (easier to ask forgiveness than permission).

    Pythonistas typically suggest that EAFP is better, with arguments in style of "what if a process creates the file between the time you test for it and the time you try to create it yourself?". This argument does not apply here, but it's the general idea. Exceptions should not be treated as too exceptional.

    Performance-wise in your case —since setting up exception managers (the try keyword) is very cheap in CPython while creating an exception (the raise keyword and internal exception creation) is what is relatively expensive— using method №2 the exception would be raised only once; afterwards, you just use the property.

提交回复
热议问题