| ▲ | formerly_proven 21 hours ago | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
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]
[red x]
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. | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| ▲ | sevensor 18 hours ago | parent | next [-] | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Last time I measured it, handling KeyError was also significantly faster than checking with “key in collection.” Also, as I was surprised to discover, Python threads are preemptively scheduled, GIL notwithstanding, so it’s possible for the key to be gone from the dictionary by the time you use it, even if it was there when you checked it. Although if you’re creating a situation where this is a problem, you probably have bigger issues. | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| ▲ | agumonkey 21 hours ago | parent | prev | next [-] | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
I thought I knew enough about python culture but TIL https://realpython.com/python-lbyl-vs-eafp/#errors-and-excep... | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| ▲ | andy99 17 hours ago | parent | prev | next [-] | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
to me something like
is fine and isn’t subject to your disadvantage. | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| ▲ | IshKebab 20 hours ago | parent | prev [-] | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
You should do normally do | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||