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
defwith the same name replaces the first - Write one method that takes different arguments, with defaults, keywords and
*args - Use
functools.singledispatchto 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.
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.
- #_books: list[Book]
- +__init__(books: list[Book])
- +search(title: str | None, author: str | None): list[str]
- +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.
- 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.
*titleson 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 thedef: it spreads the list out into separate values, as if you'd writtenadd("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.
- Line 18 makes
finda 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 forint, and line 33 forrange. Each is named_, Python's usual name for something you'll never use by name: you always callfind.- 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":
| When | Use | Example |
|---|---|---|
| Some values can be left out | Default arguments: title=None | search(author="Jane Austen") |
| Any number of the same kind of value | *args | add("Emma", "Beloved") |
| Different kinds of value, each handled its own way | @singledispatch | find("ma"), find(1965) |
| Your own classes, each handled its own way | A 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.
| Python | Java | C# | Rust | |
|---|---|---|---|---|
| Two methods, one name | The last def wins | Overloading: both kept, chosen by the types of the arguments when compiling | Overloading, as in Java | Not allowed: each function needs its own name |
| Values that can be left out | Defaults: title=None | None: write another overload | Optional parameters: string title = null | None: pass an Option |
| Passing by name | author="Jane Austen" | Not possible | author: "Jane Austen" | Not possible |
| Any number of values | *titles | String... titles | params string[] titles | Pass a slice: &[&str] |
| Choosing by type | @singledispatch, on the first value, when it runs | Overloading, on every value, when compiling | Overloading, as in Java | Traits 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.
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.
- The Python Language Reference: Function definitions: a def binds the function to a name
- The Python Tutorial: Default Argument Values
- The Python Tutorial: Arbitrary Argument Lists
- The Python Tutorial: Unpacking Argument Lists: the * in a call
- functools.singledispatch
- Glossary: single dispatch
- OMG Unified Modeling Language (UML) 2.5.1: the standard the class diagrams follow
- The Java Language Specification: 8.4.9 Overloading: two Java methods with one name
- The Java Tutorials: Passing Information to a Method or a Constructor: any number of values with ... in Java
- C# documentation: Named and Optional Arguments: values left out, and passed by name, in C#
- The Rust Reference: Functions: a Rust function has one set of parameters