Search code examples
pythonoverloadingmypy

Python function overload with mypy


I have recently started adding type definitions to my Python code and I am stuck at this problem.

Given a foo.py file:

from typing import overload


@overload
def foo(a: int) -> int: ...

@overload
def foo(b: float) -> int: ...

def foo(a: int = 0, b: float = 0) -> int:
    # implementation not relevant
    return 42

When I run mypy I get the following error:

$ mypy foo.py
foo.py:10: error: Overloaded function implementation does not accept all possible arguments of signature 2  [misc]

I cannot understand where the error is.

In Java I can do that:

interface IFoo {
        int foo(int a);
        int foo(float b);
}

public class Foo implements IFoo {
        public int foo(int a) {
                return this.foo(a, 0f);
        }

        public int foo(float b) {
                return this.foo(0, b);
        }

        private int foo(int a, float b) {
                // implementation not relevant
                return 42;
        }

        public static void main (String[] args) {
                Foo obj = new Foo();
                System.out.println(obj.foo(1));
                System.out.println(obj.foo(1f));
                System.out.println(obj.foo(1, 1f));
        }
}

Can anybody explain me what I am doing wrong in the Python code?


Solution

  • One problem with your code is that when one call your function with an argument:

    foo(x)
    

    that x is always for the a argument, thank to this signature:

    def foo(a: int) -> int: ...
    

    and your:

    def foo(b: float) -> int: ...
    

    is never matched.