Object-oriented programming · lesson 10 of 17
Parts in this lesson
Athing.titleanything with a title will do
Bclass Puzzle:no shared parent
Ctry: … except AttributeError:try first (EAFP)
Dhasattr(thing, "author")ask first (LBYL)

Duck typing

Last updated

In lesson 4.9 every item shared a parent, LibraryItem. Python doesn't need that. A function that reads .title works on anything that has a .title, whatever its class and whoever its parents are. This is duck typing. In this lesson you'll build a shelf that holds books, DVDs and jigsaw puzzles, see when a missing attribute is noticed, choose between asking first and trying first, and learn when hasattr helps and when it hides a mistake.

By the end of this lesson you can

  • Explain duck typing, and write a function that works on any object with the right attribute
  • Say when Python notices that an object is missing an attribute
  • Write the same check both ways: asking first (LBYL) and trying first (EAFP)
  • Use hasattr for something that's truly optional, and not to hide mistakes

If it walks like a duck

There's an old saying: "If it walks like a duck and quacks like a duck, it's a duck." Python treats objects the same way. It doesn't ask what class an object is. It just tries to use it, and if the object has what's needed, that's enough. This is called duck typing.

Step 1 code main.py
Edit the code, then run it again

label on line 13 reads thing.title, and that's all it needs. Book and Puzzle have no parent in common (other than object, which every class has), yet both work, because both have a title.

Line 19 is duck typing you've used since Stage 1. len works on text, a list and a dict, which are three unrelated kinds of value. Each one knows how to count itself, and len only asks. Lesson 4.11 shows how to make your own objects work with len too.

A shelf for anything with a title

The library is starting to lend jigsaw puzzles. A puzzle isn't a book or a DVD, has no year, and is nothing like a LibraryItem. This Shelf doesn't care. It keeps things in a dict by their title, so anything with a title can go on it.

No arrows between Shelf, DVD and Puzzle: the shelf only needs a title
100%
Shelf
  • #_by_title: dict[str, DVD | Puzzle]
  • +__init__()
  • +add(thing: DVD | Puzzle)
  • +titles(): list[str]
LibraryItem
  • +title: str
  • +year: int
  • +__init__(title: str, year: int)
Puzzle
  • +title: str
  • +pieces: int
  • +__init__(title: str, pieces: int)
DVD
  • Class LibraryItem; attributes: title, year; methods: __init__.
  • Class DVD; inherits from LibraryItem; no attributes of its own; no methods of its own.
  • Class Puzzle; attributes: title, pieces; methods: __init__.
  • Class Shelf; attributes: _by_title; methods: __init__, add, titles.
  • Shelf holds many DVD in _by_title.
Step 2 code main.py
Edit the code, then run it again
  • Line 22 reads thing.title and stores the thing under it. Nothing checks what class the thing is.
  • Line 25 sorts the dict. Sorting a dict sorts its keys, so titles() gives back the titles in order.
  • Line 32 shows a puzzle isn't a LibraryItem. If add had checked isinstance(thing, LibraryItem), the puzzle would have been turned away, though the shelf works fine with it.

That's the reason to leave the class check out: the shelf works with kinds of things that didn't exist when it was written, and they don't have to join a family to use it. What a thing can do matters more than what it is.

A member on the shelf

Here's an earlier draft of the shelf. It keeps things in a list and only reads their titles when asked for them. By mistake, line 24 puts a member on the shelf. Run it.

Step 3 code main.py
Edit the code, then run it again

Line 24 added a Member, and nothing complained. Line 26 even printed Added three things. The error only came when line 19 ran: 'Member' object has no attribute 'title'. Python doesn't check an object when you pass it around. It finds out it's missing something when the line that uses it runs.

That's the cost of duck typing. The traceback points at line 19, inside titles, but the mistake was made on line 24. In a bigger program the two could be in different files, minutes apart.

The shelf in step 2 doesn't have this problem, because its add reads thing.title straight away, on line 22. The same mistake there would stop on the line that made it. When an object must have something, use it, or read it, as early as you can, so the error points at the mistake.

Ask first, or try first

Sometimes an attribute really is optional. A book has an author and a DVD doesn't, and a catalogue line should show the author when there is one. There are two ways to write that.

Two ways to deal with something that might be missing
NameIn PythonHow it works
Look before you leap (LBYL)if hasattr(thing, "author"):Check first, then do it
Easier to ask forgiveness than permission (EAFP)try: … except AttributeError:Do it, and handle the error if it comes

hasattr(thing, "author") gives True if thing has an attribute called author, and False if not. It asks first.

The try and except you met in lesson 2.6 can catch AttributeError like any other error. That tries first.

Step 4 code main.py
Edit the code, then run it again

Both functions give the same lines.

  • line_lbyl (line 13) asks first, on line 14.
  • line_eafp (line 19) tries to read the author on line 21. If it's missing, line 23 gives back the title alone.

Python programmers usually write the second way. It's the same pattern as int(text) inside a try in lesson 2.6: do the thing you expect to work, and deal with the rare case when it fails.

Keep the try block small. Line 21 is the only line in it, so the except can only catch a missing author. If line 24 were inside the try too, a typo like thing.titel would be caught as well, and the program would quietly print the wrong thing instead of stopping.

hasattr, and when not to use it

hasattr is right for something that's truly optional, like the author in step 4. It's wrong for something that must be there. This shelf uses it to skip anything without a title:

Step 5 code main.py
Edit the code, then run it again

There's no error this time. Line 24 adds Sam, line 16 finds no title, and Sam is dropped without a word. Two titles come out, and nobody knows a mistake happened. An AttributeError, like the one in step 3, would at least have said so.

Three times not to use hasattr:

  • To skip something that must be there. If every thing on a shelf needs a title, let the missing one raise an error.
  • To choose what to do for each kind of object. A chain of if hasattr(...) checks is the isinstance chain from lesson 4.9 again. Let each class answer for itself with a method.
  • To be sure it's the right thing. hasattr(thing, "title") only says an attribute by that name exists. It could be None, or a number.

In other languages

This step is optional. It's for anyone who will meet Java, C# or Rust later.

Duck typing in three languages
PythonJava and C#Rust
Which objects a function acceptsAny object that has what the function usesOnly objects whose class says it is the right type or implements the interfaceOnly values whose type implements the trait
A missing method is foundWhen the line that uses it runsWhen compilingWhen compiling
Asking whether an object has somethinghasattr(thing, "title")Rarely needed: the type says. Java instanceof, C# is ask about the typeNot needed: the compiler knows

In Java, C# and Rust, a puzzle could only go on the shelf if its type said so, through a shared parent, an interface or a trait, and a member would be turned away before the program ever ran. Python gives up that early check to let any object with a title in. Lesson 4.14 shows how to write down "anything with a title" so a checking tool can catch the member early, with no shared parent. In Rust the same idea is a trait, as in Simple Rust 4.3.

Check what you learned

Three questions. Pick or type an answer, then check it.

A function reads thing.title. When does Python notice that an object passed to it has no title?
What does this program print?
def size(thing):
    try:
        return len(thing)
    except TypeError:
        return 0


print(size("Dune"), size(42))
A shelf's add uses if hasattr(thing, "title"): and quietly skips anything without a title. What's the trouble?

Sources

Every example on this page was run with Python 3.14, and its output and error messages are copied from it. These pages cover the same ground in more depth.

All sources for Simple Python