preventing creation of instance

Alexander Schmolck a.schmolck at
Wed Jun 18 17:19:37 CEST 2003

Peter Hansen <peter at> writes:

> Alexander Schmolck wrote:
> > 
> > Peter Hansen <peter at> writes:
> > > I believe raising any exception in __init__ is the way to prevent
> > > the creation of the object.  I don't think you can do this with
> > > a technique that returns None, unless you are actually calling
> > > a factory function which internally attempts to create the object
> > > and catches the exception thrown, returning None if it happens.
> > 
> > >>> class Test(object):
> > ...    def __new__(cls): return None
> > ...
> > >>> Test()
> > >>>
> > 
> > see
> D'oh!  I really ought to find a reason to learn about the
> "__new__-fangled" methods in the latest Python releases...  
> I just can't seem to find a reason to use them though (yet).

I agree with your advice of raising an exception to prevent object creation
(so this example doesn't merrit __new__, I think). However, if you want to
return e.g. always the same object (or cached objects) or (a bit more
perversely) an object of another type upon instance creation __new__ comes in
handy. I think an important advantage of __new__ over factory functions is
that this special cration mechanism is is transparently and automatically
available via instances. Thus e.g.

    def doSomething(self):
        newObject = self.__class__()
        return newObject

   newThing = type(thing)()

will do the right thing (e.g. return cached instances), without needing to
know about a factory function.


More information about the Python-list mailing list