Course topics

By WebNest Studio Engineering Team

Python Tutorial

Method Overloading in Python

In Java or C++, method overloading means defining several methods with the same name but different parameter lists, and the compiler picks one based on the arguments. Python does not support this directly: a later definition with the same name simply replaces the earlier one.

This lesson shows what happens if you try, and the Pythonic ways to get the same flexibility: default and variable arguments, type-based dispatch with functools.singledispatch and singledispatchmethod, alternative constructors, and typing.overload for type checkers.

Why it matters

Developers arriving from Java or C++ expect to write several functions with the same name and different parameters, and are surprised when only the last one exists. Python reaches the same goal in other ways, and knowing them is necessary both to write flexible functions and to answer a question that interviewers often ask of people with a Java background.

Why Classic Overloading Does Not Work

A class body is executed like normal code: def area(self, r) followed by def area(self, w, h) binds the name area twice, and only the last function survives. Calling it with one argument then raises TypeError.

Default Arguments and *args

Most overloading needs are met with optional parameters: def area(self, a, b=None) computes a square when b is missing and a rectangle otherwise. *args and **kwargs handle a variable number of arguments.

Dispatch on Type

functools.singledispatch turns a function into a generic function whose implementation is chosen by the type of the first argument; register implementations with @func.register. For methods, functools.singledispatchmethod dispatches on the first argument after self.

typing.overload

@typing.overload declares several signatures for type checkers and IDEs, followed by one real implementation. It documents the accepted combinations but performs no runtime dispatch.

Examples

The last definition wins

Python
class Calculator:
    def add(self, a, b):
        return a + b

    def add(self, a, b, c):          # replaces the first add
        return a + b + c

calc = Calculator()
print(calc.add(1, 2, 3))
try:
    calc.add(1, 2)
except TypeError as e:
    print("TypeError:", e)
Output
6
TypeError: Calculator.add() missing 1 required positional argument: 'c'

Overloading with default arguments and *args

Python
class Calculator:
    def add(self, *numbers):
        return sum(numbers)

    def area(self, a, b=None):
        return a * a if b is None else a * b

calc = Calculator()
print(calc.add(1, 2), calc.add(1, 2, 3, 4))
print(calc.area(5), calc.area(4, 6))
Output
3 10
25 24

Type-based dispatch with singledispatch and singledispatchmethod

Python
from functools import singledispatch, singledispatchmethod

@singledispatch
def describe(value):
    return f"something: {value!r}"

@describe.register
def _(value: int):
    return f"integer with {len(str(abs(value)))} digits"

@describe.register
def _(value: list):
    return f"list of {len(value)} items"

print(describe(12345), "|", describe([1, 2]), "|", describe(3.5))

class Formatter:
    @singledispatchmethod
    def format(self, value):
        return str(value)

    @format.register
    def _(self, value: float):
        return f"{value:.2f}"

    @format.register
    def _(self, value: dict):
        return ", ".join(f"{k}={v}" for k, v in value.items())

f = Formatter()
print(f.format(7), f.format(3.14159), f.format({"a": 1, "b": 2}))
Output
integer with 5 digits | list of 2 items | something: 3.5
7 3.14 a=1, b=2

typing.overload for precise type hints

Python
from typing import overload

@overload
def parse(value: str) -> int: ...
@overload
def parse(value: bytes) -> str: ...

def parse(value):
    if isinstance(value, bytes):
        return value.decode()
    return int(value)

print(parse("42") + 1, parse(b"hello").upper())
Output
43 HELLO

Common Mistakes

  • Defining several methods with the same name expecting Java-style overloading.
  • Writing long isinstance chains where singledispatch would be clearer.
  • Expecting typing.overload to dispatch at runtime — it only informs type checkers.
  • Using *args everywhere so the function signature no longer documents its inputs.

Exercise

Use functools.singledispatch to write a function describe that behaves differently for an int, a str and a list.

Expected output: int: 5, str: hi, list of 2 items (one per line)

Python · starter code
from functools import singledispatch


@singledispatch
def describe(value):
    return "unknown"


# TODO: register a version for int   -> "int: 5"
# TODO: register a version for str   -> "str: hi"
# TODO: register a version for list  -> "list of 2 items"


print(describe(5))
print(describe("hi"))
print(describe([1, 2]))
Show hints
  • Each version is decorated with @describe.register and has a type hint on its first parameter.
  • The function name for the registered versions does not matter; _ is commonly used.
Show solution
Python · solution
from functools import singledispatch


@singledispatch
def describe(value):
    return "unknown"


@describe.register
def _(value: int):
    return f"int: {value}"


@describe.register
def _(value: str):
    return f"str: {value}"


@describe.register
def _(value: list):
    return f"list of {len(value)} items"


print(describe(5))
print(describe("hi"))
print(describe([1, 2]))

Quick quiz

1. A class defines def area(self, r) and then def area(self, w, h). What happens?

  • A. Both are available
  • B. A syntax error
  • C. The second definition replaces the first
  • D. The first replaces the second
Show answer

C. A name can refer to only one function. Calling area with one argument now fails.

2. What is the simplest way to let a function be called with different numbers of arguments?

  • A. Default values and *args
  • B. Define it several times
  • C. A separate class for each case
  • D. It cannot be done
Show answer

A. One function with optional parameters covers most uses of overloading.

3. On what does functools.singledispatch choose which version to run?

  • A. The number of arguments
  • B. The type of the first argument
  • C. The name of the caller
  • D. The return type
Show answer

B. singledispatchmethod does the same for methods, using the first argument after self.

Interview questions

Does Python support method overloading?

Show answer

Not in the sense used in Java. Functions are stored by name, so a second definition replaces the first. The same result is achieved with default argument values, with *args and **kwargs, by checking the type of an argument inside the function, or with functools.singledispatch, which selects an implementation from the type of the first argument.

What is typing.overload for?

Show answer

It is for type checkers only. Several signatures decorated with @overload describe the different ways a function may be called and what each returns, followed by one real implementation. It gives editors and tools such as mypy precise information, but it has no effect at runtime and does not create separate functions.

Key Points to Remember

  • Python keeps only the last definition of a name; there is no classic overloading.
  • Default arguments and *args/**kwargs cover most overloading needs.
  • functools.singledispatch / singledispatchmethod dispatch on argument type.
  • Alternative constructors (@classmethod) replace constructor overloading.
  • typing.overload documents multiple signatures for type checkers.

Practice in the playground

Write and run your own code for this topic, or start from the exercise or an example. Runs Python in your browser. Your code for each topic is kept in this browser.

Run the examples

Change an input, predict the result, then compare it with the output. Explain why the result changes.

WebNest Studio

Written by

WebNest Studio Engineering Team

Practical lessons from developers working with Java, Python, React, databases and production systems.

Led by Vansh Duggal, Founder, WebNest Studio · Full-stack & software engineering