Python 用 mypy 重载函数

Python function overload with mypy

我最近开始在我的 Python 代码中添加类型定义,但我被这个问题困住了。

给定一个 foo.py 文件:

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

当我 运行 mypy 我得到以下错误:

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

我不明白错误在哪里。

在 Java 我可以做到:

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));
        }
}

谁能解释一下我在 Python 代码中做错了什么?

您的代码的一个问题是,当有人使用参数调用您的函数时:

foo(x)

x 总是用于 a 参数,多亏了这个签名:

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

和你的:

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

从未匹配。