0

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?

dapicester
  • 3
  • 1
  • 4

1 Answers1

0

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.

hussic
  • 1,816
  • 9
  • 10
  • I know in Python I can explicitely use foo(a=x) or foo(b=x), but my issue is that I get the error on the definition of foo(), not on its usage. – dapicester Feb 15 '22 at 06:57
  • Mypy try to guess all possible uses of code also if not used at all. – hussic Feb 15 '22 at 11:01
  • Thanks, I got it now. To avoid that I had to mandate the use of keyword arguments (https://www.python.org/dev/peps/pep-3102/) to explicitly avoid the case where foo(x). – dapicester Feb 16 '22 at 09:57
  • Yes, often overload variants in typeshed stubs have an `...,*,...` form. – hussic Feb 16 '22 at 10:28