Calling constructor but not initializer

Steven D'Aprano steve at
Fri Sep 21 16:18:55 CEST 2007

I have a class that has a distinct "empty" state. In the empty state, it 
shouldn't have any data attributes, but it should still have methods.

The analogy is with a list: an empty list still has methods like append() 
etc. but it has no "data", if by data you mean items in the list.

I can construct an empty instance in the __new__ constructor, and I can 
initialize an non-empty instance in the __init__ initializer, but I can't 
think of any good way to stop __init__ from being called if the instance 
is empty. In pseudo-code, I want to do something like this:

class Parrot(object):
    def __new__(cls, data):
        construct a new empty instance
        if data is None:
            return that empty instance
            call __init__ on the instance to populate it
            return the non-empty instance

but of course __init__ is automatically called.

Any suggestions for doing something like this?


More information about the Python-list mailing list