What does Duck Typing, EAFP, LBYL programming mean?
“If it looks like a duck, swims like a duck, and quacks like a duck… it’s probably a duck.”
Its a programming style where we dont check if an object is of proper type before invoking methods from that object. We just do it. Programmatically, we dont use tests using type() or isinstance().
An example of duck typing code in python would be as below
def stream_stuff(obj):
obj.read() # We assume it’s a file-like thingy
We dont test if obj is of a proper type that can have the read() method.
Note: Duck-typing can be complemented with abstract base classes.
How? The thinking is: “I get duck typing, but can we at least define what a duck is supposed to do?”
In the above sentence, the duck is the object ie, obj and obj is an instance of a class which inherits from python's abstract base class. This helps to define what methods obj can have with certainty.
==Abstract base classes formalize duck typing.==
Duck typing often goes hand in hand with EAFP = "Easier than asking for forgiveness than permission".
EAFP is a common Python coding style which assumes the existence of valid keys or attributes and catches exceptions if the assumption proves false. Its clean and fast and is characterized by the presence of many try and except statements.
try:
value = my_dict['key'] # We just assume that key is present in my_dict
except KeyError:
value = 'default' # If it doesnt have then we ask for forgiveness which is easier
EAFP contrasts to LBYL = "Look before you leap" programming style.
This coding style explicitly tests for pre-conditions before making calls or lookups. This style is characterized by the presence of many if statements.
In other words, you check everything before you do it.
Both LBYL and EAFP are like siblings in the defensive programming family:
- LBYL: Better safe than sorry.
- EAFP: Just send it. I’ve got the extinguisher.