Checking for member existence in Python

PierreBdR picture PierreBdR · Oct 15, 2008 · Viewed 15.5k times · Source

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 this:

class Foo(object):
    @classmethod
    def singleton(self):
        if not hasattr(self, 'instance'):
            self.instance = Foo()
        return self.instance

But you can also do this:

class Foo(object):
    @classmethod
    def singleton(self):
        try:
            return self.instance
        except AttributeError:
            self.instance = Foo()
            return self.instance

Is one method better of the other?

Edit: Added the @classmethod ... But note that the question is not about how to make a singleton but how to check the presence of a member in an object.

Edit: For that example, a typical usage would be:

s = Foo.singleton()

Then s is an object of type Foo, the same each time. And, typically, the method is called many times.

Answer

tzot picture tzot · Oct 15, 2008

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.