Skip to main content

python-duck-typing

#post

python-duck-typing

  • Python code style that encourages you to care about what an object is capable of rather than what it is
  • As in, if it walks like a duck and quacks like a duck, for all intents and purposes, it’s a duck
  • So, don’t care about the type; care about the behavior (its traits)
    • Can it quack?
    • Can it fly?
    • Instead of “is it a duck?”
  • Is this in opposition to static typing (which defines what things are)?
  • Does not mean LBYL by checking if it can quack/fly (e.g. if hasattr(thing, 'quack'))
  • Instead, just try to make it quack and handle failure if it occurs
def quack_and_fly(thing):
    try:
        thing.quack()
        thing.fly()
    except AttributeError as e:
        print(e)