views:

52

answers:

1

I have a class that knows its existing instances. Sometimes I want the class constructor to return an existing object instead of creating a new one.

class X:
    def __new__(cls, arg):
        i = f(arg)
        if i:
            return X._registry[i]
        else:
            return object.__new__(cls)
    # more stuff here (such as __init_, _registry, etc.)

Of course, if the first branch is executed, I don't need __init__, but it's invoked anyways. What's a good way to tell __init__ to do nothing?

I can probably just add some attribute to keep track of whether __init__ has run yet, but perhaps there's a better way?

+1  A: 

Use a factory, i.e.

_x_singleton = None

def XFactory():
    global _x_singleton

    if _x_singleton is None:
        _x_singleton = X()
    return _x_singleton

or use a "create" classmethod in your class that behaves the way you want it to,

class X(object):
    instance = None
    def __init__(self):
        # ...
    @classmethod
    def create(cls):
        if cls.instance is None:
            cls.instance = cls()
        return cls.instance

You might even consider making __init__ raise an exception if some condition isn't met (i.e. self.instance not being None)

Ivo van der Wijk