Object-oriented programming · lesson 12 of 17
Parts in this lesson
Adef search(self, title=None, author=None):defaults and keywords
Bdef add(self, *titles):any number of values
C@singledispatchone function for each type
D@find.register(int)add a version for a type

One name, different arguments

Last updated

A catalogue search might get a title, an author, both, or a whole list of titles. Java and C# let you write several methods with the same name, one for each set of arguments. Python doesn't. In this lesson you'll see what happens when you try, then meet the tools Python uses instead: default and keyword arguments, *args, and functools.singledispatch, which picks a function by the kind of value it's given.

By the end of this lesson you can

  • Explain why a second def with the same name replaces the first
  • Write one method that takes different arguments, with defaults, keywords and *args
  • Use functools.singledispatch to pick a function by the type of its first argument

Two searches with one name

A catalogue needs to search by title, and sometimes by title and author. In Java you'd write two methods called search with different parameters, and the language would pick one for each call. Here's the same idea in Python. Run it.

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

Line 23, with two values, worked. Line 24, with one, stopped: Catalogue.search() missing 1 required positional argument: 'author'. The one-value search on line 11 is gone.

A def is an assignment. It makes a function and gives it a name, the way x = 1 gives a value a name. Inside a class, the name belongs to the class. So line 14 does to search what x = 2 does to x: the name now means the new function, and the old one is thrown away. Python has no method overloading, which means keeping several methods with one name and choosing between them by their arguments. The last def wins.

Python doesn't warn you about this. A checker like mypy from lesson 2.11 does: it reports a second search as already defined. Python's answer is one search that can take different arguments, as the next steps show.

Default and keyword arguments

You met defaults and keyword arguments in lessons 1.8 and 2.5. Here they make one search that handles everything the two tried to. Both parameters default to None, meaning "not given", and each one is only checked if it was given.

One search method with optional values
100%
Catalogue
  • #_books: list[Book]
  • +__init__(books: list[Book])
  • +search(title: str | None, author: str | None): list[str]
Book
  • +title: str
  • +author: str
  • +__init__(title: str, author: str)
  • Class Book; attributes: title, author; methods: __init__.
  • Class Catalogue; attributes: _books; methods: __init__, search.
  • Catalogue holds many Book in _books.
Step 2 code main.py
Edit the code, then run it again
  • Line 14 skips a book only if a title was given (title is not None) and this book's title is different. Line 16 does the same for the author.
  • Line 27 passes a title the usual way, by position.
  • Line 28 passes only an author, by name. Without the name, "Jane Austen" would be taken as the title.
  • Line 29 passes both. No book is Emma by Frank Herbert, so the list is empty.
  • Line 30 passes nothing, and every book matches.

One method, four ways to call it. Keyword arguments make each call say what its values mean: search(author="Jane Austen") can't be misread.

Any number of arguments with *args

Sometimes the difference is only how many values there are. Java would have add(title), add(title1, title2) and so on. In Python, the *args from lesson 2.5 collects any number of values into a tuple.

Step 3 code main.py
Edit the code, then run it again
  • *titles on line 5 collects every value passed: one on line 12, three on line 13, none on line 14.
  • Line 16 has the titles already in a list. A star in a call, *returned, does the opposite of the star in the def: it spreads the list out into separate values, as if you'd written add("The Hobbit", "Persuasion").

Choosing by type with singledispatch

Sometimes it's the kind of value that should decide. A find that gets text should search titles, one that gets a whole number should search years, and one that gets a range of years should search between them. You could write an isinstance chain, but lesson 4.9 showed where those lead. Your own classes can each have a method. But str, int and range are built into Python, and you can't add a method to them.

functools.singledispatch solves this. It's a decorator, like @classmethod in lesson 3.4, that turns a function into one that can have a separate version for each type.

Step 4 code main.py
Edit the code, then run it again
  • Line 18 makes find a single-dispatch function. Its own body, on line 20, runs only for a type nobody has registered, and says so.
  • @find.register(str) on line 23 adds a version for text. Line 28 adds one for int, and line 33 for range. Each is named _, Python's usual name for something you'll never use by name: you always call find.
  • When you call find(1965), Python looks at the type of the first value, int, and runs that version.

Add print(find(19.65)) at the end. No version is registered for float, so line 20 raises the TypeError.

"Single dispatch" means the choice is made by one argument, the first. For a method, where the first argument is always self, there's functools.singledispatchmethod, which looks at the next one.

Which one to use

Each tool fits a different reason for wanting "one name, different arguments":

One name, different arguments
WhenUseExample
Some values can be left outDefault arguments: title=Nonesearch(author="Jane Austen")
Any number of the same kind of value*argsadd("Emma", "Beloved")
Different kinds of value, each handled its own way@singledispatchfind("ma"), find(1965)
Your own classes, each handled its own wayA method in each class (lesson 4.9)item.loan_days()

Reach for defaults first: they're the simplest, and keyword arguments make the calls easy to read. Use singledispatch when the type of the value really changes the work, especially for built-in types. And if the types are your own classes, give each class its own method: that's polymorphism through overriding, from lesson 4.9.

In other languages

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

One name, different arguments in four languages
PythonJavaC#Rust
Two methods, one nameThe last def winsOverloading: both kept, chosen by the types of the arguments when compilingOverloading, as in JavaNot allowed: each function needs its own name
Values that can be left outDefaults: title=NoneNone: write another overloadOptional parameters: string title = nullNone: pass an Option
Passing by nameauthor="Jane Austen"Not possibleauthor: "Jane Austen"Not possible
Any number of values*titlesString... titlesparams string[] titlesPass a slice: &[&str]
Choosing by type@singledispatch, on the first value, when it runsOverloading, on every value, when compilingOverloading, as in JavaTraits and generics, when compiling

Java and C# choose between overloads when compiling, by looking at the types of every argument. Python's singledispatch chooses when the program runs, and only by the first. Rust has no overloading at all: two functions need two names, and traits do the rest, as in Simple Rust 4.3.

Check what you learned

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

What does this program print?
def due(days):
    return days


def due(days, renewals):
    return days * (renewals + 1)


print(due(7, 1))
A search must work with a title, an author, or both. What's the Python way?
With @singledispatch, what decides which version of the function runs?

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