Concurrency Implications of Using EAFP / LBYL

When writing parallel / multi-threaded code in Python, is it especially important to follow the idiom “Easier to apologize than permission” (EAFP), and not “Look Before You Leap” (LBYL)? Python's exceptionally dynamic nature means that almost nothing (like removing an attribute) can happen between a look and a jump - if so, what is the point? For example, consider

# LBYL
if hasattr(foo, 'bar'):
    baz = foo.bar

vs

# EAFP
try:
    baz = foo.bar
except AttributeError:
    pass

In the LBYL example, the attribute barcan disappear with foobefore the actual call is made foo.bar, so that you get something from the check? If there is a risk that the attribute may disappear, you will need locks and / or try / except clauses.

, , " " , - . .

+3
1

. :

, : : , LBYL.

: : , :

item = getattr(foo, 'bar', None)
if item is None:
    ....
else:
    ....
+3

Source: https://habr.com/ru/post/1704738/


All Articles