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

Rob Gaddi rgaddi at highlandtechnology.invalid
Mon Nov 4 14:41:34 EST 2019


On 11/4/19 10:59 AM, R.Wieser wrote:
> Rob,
> 
>> Returning None will specifically NOT accomplish the thing you want;
>> nothing ever checks the return value of __init__.
> 
> I thought to have read that when you return a none from it the object itself
> would return a placeholder singleton.
> 
>> Raise an exception.
> 
> Yeah, that was what I was thinking too - up until the moment I realized that
> the than-needed "try" around creating the object would catch /all/ errors in
> there, and not just the "can't initialize" one ...   I might have
> misunderstood that though.
> 
> Regards,
> Rudy Wieser
> 
> 

A function with no explicit return returns None; every function returns 
something.  __init__ is not an object creation function (that's __new__), it 
initializes an already created object that we traditionally call "self".

When you exception out of __init__, it causes that initial assignment of the 
newly created (but only halfway initialized) object to fail, so no one winds up 
holding a reference to it.  Because no one's holding a reference to it, it gets 
deleted (one day).

That's why if you for instance, open a serial port in an __init__ routine, and 
something fails, you want to catch the exception there in __init__, explicitly 
close that serial port, and reraise the exception.  Otherwise that port still 
has an object open against it until Python gets around to closing it.

The exception you raise should indicate why it failed, such as a TypeError or 
ValueError if one of the arguments was some flavor of stupid, or a 
ConnectionRefusedError.  Often the exception will already raise itself, and it's 
simply a matter of not getting in its way.  But if the concern is the 
try..except block around the initialization catching too many things, then 
either a) your try block is too long and encompasses too many unrelated lines of 
code, or b) your except condition is too broad.  Don't "except Exception".  Only 
catch specific exceptions where you can provide benefit by doing do.

-- 
Rob Gaddi, Highland Technology -- www.highlandtechnology.com
Email address domain is currently out of order.  See above to fix.


More information about the Python-list mailing list