Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bad form to return None in __init__ in python

I was tinkering around with some classes and I came upon a situation where I wanted to cut off __init__ before it got a chance to do anything more. To do so, I simply put a null return statement at the end of the block I wanted to cut off at. For example:

class Example(object):
    def __init__(self):
        #lots and lots of code
        if so_and_so:
            return

Is it bad form to return inside __init__, even if it's just under this circumstance?

like image 789
user3002473 Avatar asked Sep 03 '26 19:09

user3002473


2 Answers

For any function, not only __init__, using plain return is equivalent to returning None, and if you don't use return in a function, None is implicitly returned anyway.

Therefor, it is perfectly fine to use return inside __init__.

(The exception to the rule above is generator functions, inside which you may only use return and not return None, so these are not equivalent inside generator functions).

Returning in the middle of __init__ will simply cut off object's initialization. It will not prevent the object from being created, nor interrupt program's flow in any way.

like image 94
shx2 Avatar answered Sep 05 '26 08:09

shx2


How long is a piece of string? If you don't need to initialize any further, then there's no point in continuing. Since None is returned implicitly at the end anyway (and in fact should be the only thing ever returned by __init__()), returning it early if initialization has been completed is fine.

OTOH, if you need to abort initialization then you should raise an exception instead.

like image 28
Ignacio Vazquez-Abrams Avatar answered Sep 05 '26 09:09

Ignacio Vazquez-Abrams



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!