Skip to content
Advertisement

How to overload a function with default parameters in Python

So I have the following (simplified) code

JavaScript

which I don’t know how to get to typecheck.

If I don’t add the overloads mypy complains that I might be indexing into a tuple with a str index.

The as_tuple parameter defaults to false, so mypy should be able to infer that I’m using the first overload when not providing the second and the third argument to the function (as the actual implementation has default parameters).

However what actually happens is that mypy complains that none of the provided overloads match, since it thinks that I need to provide the last two arguments as well.

When I just copy paste the default arguments to each of the overloads, mypy complains that I can’t assign False to as_tuple: Literal[True].

Is there an option to get this to typecheck the way it works at runtime? I really don’t want to modify the actual signature as the function is used widely throughout our tests.

Advertisement

Answer

If you let parameters in some of your overloads take defaults, then you don’t need as many overloads. You probably also want an extra overload for when you passed a boolean to as_tuple:

JavaScript

Running this gives:

JavaScript
Advertisement