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

Chris Angelico rosuav at gmail.com
Tue Nov 5 02:43:45 EST 2019


On Tue, Nov 5, 2019 at 6:26 PM R.Wieser <address at not.available> wrote:
> > It is considered totally OK to use exception handling as a control
> > flow mechanism in Python.
>
> I'm not sure what exactly you mean with "a control flow mechanism", but as
> several methods throw exceptions themselves I will have no choice in having
> to deal with them.
>

"Control flow" is anything that changes the order that your code runs.
That can be as simple as an "if" statement, or as complicated as
asynchronicity and yield points. In this context, exception handling
is most definitely a form of control flow, but the point is that it is
*normal* control flow. In a number of languages, exceptions always and
only mean errors - you can catch them, but that always represents
coping with an error in some way. In Python, they're an everyday
occurrence. Consider:

it = iter(range(5))
while True:
    try: i = next(it)
    except StopIteration: break
    print(i)


This is more-or-less equivalent to:

for i in range(5):
    print(i)

The call to next() is going to either return the next value, or raise
StopIteration to say "nothing more to see here". That's a common thing
in Python. There are some contexts in which there's no possible
"sentinel" object that could be returned - it's perfectly legal for
the function to return literally any object at all - so it needs some
other way to signal that it doesn't have anything to return, and that
"other way" is to raise some specific exception.

This is what's usually meant by "exceptions as a control flow
mechanism" - that perfectly ordinary constructs like 'for' loops use
exceptions to signal what they should do.

ChrisA


More information about the Python-list mailing list