Using a class attribute without knowing it's existence.

What to do without a Case/Switch feature.

Wrong Ways

My evolution to finding this pattern. Lets say you have a class and you want to see if it has an attribute. The first way I thought to do this was:

Very wrong way
class A:
    ...
a = A()
if 'attribute' is in dir(a):
    #do something
else:
    #do something else

Then I found out about the hasattr function.

less wrong way
class A:
    ...
a = A()
if hasattr(a,'attribute'):
    #do something
else:
    #do something else

Right Way - "Easier to Ask for Forgiveness instead of Permission"

The Python community generally prefers "EAFP" rather than "LBYL" (Look Before Your Leap).

What this means in practice is to use a try and except block.

Right Way
class A:
    ...
a = A()
try:
    a.attribute
except:
    #do something else

Sources and References

Last updated