Domanda

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?

È stato utile?

Soluzione

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.

Altri suggerimenti

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.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top