OOP - how to abort an __init__ when the initialisation code fails ?

Luciano Ramalho luciano at ramalho.org
Mon Nov 4 13:36:00 EST 2019


Sorry, I responded only to the OP. My response:

"""A failed __init__ should raise an appropriate exception. A bare
return or returning None is what any __init__ is expected to do in the
normal case, so it signals success."""

Actually, the Python interpreter *does* check the return of __init__.
If it is anything other than None, Python 3 raises TypeError when you
try to create an instance:

>>> class X:
...        def __init__(self):
...            return 1
...
>>> x = X()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: __init__() should return None, not 'int'

Cheers,

Luciano





On Mon, Nov 4, 2019 at 2:31 PM Rob Gaddi
<rgaddi at highlandtechnology.invalid> wrote:
>
> On 11/4/19 7:32 AM, R.Wieser wrote:
> > Hello all,
> >
> > The whole question: How should I handle failed initialisation code inside
> > the __init__ of an object ?
> >
> > I've seen an example doing a plain "return" (of the value "none""), but have
> > no idea if that is all it takes.
> >
> > Also, I wonder what happens to the object itself.   Does it still exist and
> > only gets actually destroyed at the next garbage-collection (because of a
> > zero reference count), or is it directly discarded (without having called
> > the __del__ method) ?
> >
> > Regards,
> > Rudy Wieser
> >
> >
>
> Raise an exception.  Returning None will specifically NOT accomplish the thing
> you want; nothing ever checks the return value of __init__.
>
> --
> Rob Gaddi, Highland Technology -- www.highlandtechnology.com
> Email address domain is currently out of order.  See above to fix.
> --
> https://mail.python.org/mailman/listinfo/python-list



-- 
Luciano Ramalho
|  Author of Fluent Python (O'Reilly, 2015)
|     http://shop.oreilly.com/product/0636920032519.do
|  Technical Principal at ThoughtWorks
|  Twitter: @ramalhoorg


More information about the Python-list mailing list