logoalt Hacker News

IshKebabtoday at 9:08 AM2 repliesview on HN

Using exceptions for flow control has always been a bad idea, despite what they might have said. Perhaps they are generating that message lazily though?

On the other hand it's not like Python really cares about performance....


Replies

formerly_proventoday at 10:54 AM

All iterators in Python use exceptions for flow control, as do all context managers for the abort/rollback case, and it is generally considered Pythonic to use single-indexing (EAFP) instead of check-then-get (LBYL) - generally with indexing and KeyError though and less commonly with attribute access and AttributeError.

[heavy green check mark]

    try:
        data = collection['key']
    except KeyError:
        data = ..try something else..
[red x]

    if 'key' in collection:
         data = collection['key']
    else:
         data = ..try something else..
The latter form also has the genuine disadvantage that nothing ensures the two keys are the same. I've seen typos there somewhat often in code reviews.
show 2 replies
amlutotoday at 9:11 AM

I would like to introduce you to StopIteration.