An Alternative to Method Overloading

Learn an alternative to method overloading with the help of several coding examples.

We'll cover the following

Method overloading

One prominent feature of many object-oriented programming languages is a tool called method overloading. Method overloading refers to having multiple methods with the same name that accept different sets of parameters. In statically typed languages, this is useful if we want to have a method that accepts either an integer or a string, for example. In non-object-oriented languages, we might need two functions, called add_s and add_i, to accommodate such situations. In statically typed object-oriented languages, we’d need two methods, both called add, one that accepts strings, and one that accepts integers.

In Python, we’ve already seen that we only need one method, which accepts any type of object. It may have to do some testing on the object type (for example, if it is a string, convert it to an integer), but only one method is required.

The type hints for a parameter that can take on multiple types can become rather complex. We’ll often have to use a typing.Union hint to show that a parameter can have values from Union[int, str]. This definition clarifies the alternatives so mypy can confirm that we’re using the overloaded function properly.

We have to distinguish between two varieties of overloading here:

  • Overloading parameters to allow alternative types using Union[...] hints
  • Overloading the method by using more complex patterns of parameters

Example

For example, an email message method might come in two versions, one of which accepts a parameter for the from email address. The other method might look up a default from email address instead. Some languages force us to write multiple methods with the same name and different parameter patterns. Python doesn’t permit multiple definitions of methods with the same name, but it does provide a different, equally flexible way to specify variant parameters.

We’ve seen some of the possible ways to send argument values to methods and functions in previous examples, but now we’ll cover all the details. The simplest function accepts no parameters. We probably don’t need an example, but here’s one for completeness:

Get hands-on with 1400+ tech skills courses.