AskOverflow.Dev

AskOverflow.Dev Logo AskOverflow.Dev Logo

AskOverflow.Dev Navigation

  • 主页
  • 系统&网络
  • Ubuntu
  • Unix
  • DBA
  • Computer
  • Coding
  • LangChain

Mobile menu

Close
  • 主页
  • 系统&网络
    • 最新
    • 热门
    • 标签
  • Ubuntu
    • 最新
    • 热门
    • 标签
  • Unix
    • 最新
    • 标签
  • DBA
    • 最新
    • 标签
  • Computer
    • 最新
    • 标签
  • Coding
    • 最新
    • 标签
主页 / coding / 问题 / 79101944
Accepted
Abhijit Sarkar
Abhijit Sarkar
Asked: 2024-10-18 19:45:32 +0800 CST2024-10-18 19:45:32 +0800 CST 2024-10-18 19:45:32 +0800 CST

mypy 关于 numpy.apply_along_axis 的警告

  • 772

编辑 2024 年 10 月 18 日:

下面显示了该问题的一个更为简单的重现。

mypy_arg_type.py:

import numpy as np
from numpy.typing import NDArray
import random

def winner(_: NDArray[np.bytes_]) -> bytes | None:
    return b"." if bool(random.randint(0, 1)) else None

board = np.full((2, 2), ".", "|S1")
for w in np.apply_along_axis(winner, 0, board):
    print(w)

>> python mypy_arg_type.py

b'.'
None

>> mypy mypy_arg_type.py

mypy_arg_type.py:9: error: Argument 1 to "apply_along_axis" has incompatible type "Callable[[ndarray[Any, dtype[bytes_]]], bytes | None]"; expected "Callable[[ndarray[Any, dtype[Any]]], _SupportsArray[dtype[Never]] | _NestedSequence[_SupportsArray[dtype[Never]]]]"  [arg-type]
mypy_arg_type.py:9: note: This is likely because "winner" has named arguments: "_". Consider marking them positional-only
Found 1 error in 1 file (checked 1 source file)

原始问题:

我正在研究一个问题,即根据棋盘上棋子的位置来确定四子连珠A游戏的获胜者。棋盘尺寸为 6x7,每列标有从到 的字母G。如果有获胜者,则在一行、一列、对角线或反对角线上有 4 个相同颜色的棋子。

例子:

输入:["A_Red", "B_Yellow", "A_Red", "B_Yellow", "A_Red", "B_Yellow", "G_Red", "B_Yellow"]

木板:

R Y . . . . R
R Y . . . . .
R Y . . . . .
. Y . . . . .
. . . . . . .
. . . . . . .

优胜者:Yellow

以下代码决定获胜者。

import itertools
import numpy as np
from numpy.typing import NDArray

def who_is_winner(pieces: list[str]) -> str:
    def parse_board() -> NDArray[np.bytes_]:
        m, n = 6, 7
        indices = [0] * n
        # https://numpy.org/doc/stable/user/basics.strings.html#fixed-width-data-types
        # One-byte encoding, the byteorder is ‘|’ (not applicable)
        board = np.full((m, n), ".", "|S1")
        for p in pieces:
            col = ord(p[0]) - ord("A")
            board[indices[col], col] = p[2]
            indices[col] += 1

        return board

    def winner(arr: NDArray[np.bytes_]) -> np.bytes_ | None:
        i = len(arr)
        xs = next(
            (xs for j in range(i - 3) if (xs := set(arr[j : j + 4])) < {b"R", b"Y"}),
            {None},
        )
        return xs.pop()

    def axis(x: int) -> np.bytes_ | None:
        # https://numpy.org/doc/2.0/reference/generated/numpy.apply_along_axis.html#numpy-apply-along-axis
        # Axis 0 is column-wise, 1 is row-wise.
        return next(
            (w for w in np.apply_along_axis(winner, x, board) if w is not None), None
        )

    def diag(d: int) -> np.bytes_ | None:
        # https://numpy.org/doc/stable/reference/generated/numpy.diagonal.html#numpy-diagonal
        # Diagonal number is w.r.t. the main diagonal.
        b = board if bool(d) else np.fliplr(board)
        return next(
            (w for d in range(-3, 4) if (w := winner(b.diagonal(d))) is not None), None
        )

    board = parse_board()
    match next(
        (
            w
            for f, i in itertools.product((axis, diag), (0, 1))
            if (w := f(i)) is not None
        ),
        None,
    ):
        case b"Y":
            return "Yellow"
        case b"R":
            return "Red"
        case _:
            return "Draw"

但是,这会产生如下的 mypy 违规:

error: Argument 1 to "apply_along_axis" has incompatible type "Callable[[ndarray[Any, dtype[bytes_]]], bytes_ | None]"; expected "Callable[[ndarray[Any, dtype[Any]]], _SupportsArray[dtype[bytes_]] | _NestedSequence[_SupportsArray[dtype[bytes_]]]]"  [arg-type]
note: This is likely because "winner" has named arguments: "arr". Consider marking them positional-only

根据apply_along_axis的文档,它应该返回一个值,这与上面的代码一致。

如何修复此违规?使函数winner仅定位于某一位置并没有什么区别,只是建议消失了。

我正在使用 Python 3.12.5 和 mypy 1.11.2。

python
  • 2 2 个回答
  • 63 Views

2 个回答

  • Voted
  1. Best Answer
    Abhijit Sarkar
    2024-10-19T15:57:14+08:002024-10-19T15:57:14+08:00

    通过研究 的重载签名apply_along_axis,我得出结论,它没有定义为返回None,从而导致 mypy 违规。但是没有真正的理由不返回None,我已经为此开了一个mypy 票。我们将看看它是否会被踢到 numpy。

    过载 1:

    def [_P`-1, _SCT: generic] apply_along_axis(func1d: Callable[[ndarray[Any, dtype[Any]], **_P], _SupportsArray[dtype[_SCT]] | _NestedSequence[_SupportsArray[dtype[_SCT]]]], axis: SupportsIndex, arr: Buffer | _SupportsArray[dtype[Any]] | _NestedSequence[_SupportsArray[dtype[Any]]] | bool | int | float | complex | str | bytes | _NestedSequence[bool | int | float | complex | str | bytes], *args: _P.args, **kwargs: _P.kwargs) -> ndarray[Any, dtype[_SCT]]
    

    过载2:

    def [_P`-1] apply_along_axis(func1d: Callable[[ndarray[Any, dtype[Any]], **_P], Buffer | _SupportsArray[dtype[Any]] | _NestedSequence[_SupportsArray[dtype[Any]]] | bool | int | float | complex | str | bytes | _NestedSequence[bool | int | float | complex | str | bytes]], axis: SupportsIndex, arr: Buffer | _SupportsArray[dtype[Any]] | _NestedSequence[_SupportsArray[dtype[Any]]] | bool | int | float | complex | str | bytes | _NestedSequence[bool | int | float | complex | str | bytes], *args: _P.args, **kwargs: _P.kwargs) -> ndarray[Any, dtype[Any]]
    

    我修改了该函数winner,使其返回一个空字节字符串(b"")而不是None,并将所有返回类型替换为np.bytes_。bytes这样就解决了问题。

    • 0
  2. shadab
    2024-10-19T08:06:32+08:002024-10-19T08:06:32+08:00

    为自定义函数添加类型注释:当 Mypy 不知道输入/输出的类型时,它经常会感到困惑。通过明确注释自定义函数,您可以为 Mypy 提供一些帮助。

    例如:

    import numpy as np
    from typing import Any
    
    def custom_function(arr: np.ndarray) -> Any:
        # Your function logic
        return np.sum(arr)
    

    对引起警告的行使用 # type: ignore:如果您无法消除警告,并且您确信代码按预期工作,您可以通过在该行中添加 # type: ignore 来告诉 Mypy 忽略它。它不适合长期使用,但它是一个快速修复:

    result = np.apply_along_axis(custom_function, axis=0, arr=my_array)  # type: ignore
    

    考虑使用 Mypy 的 NumPy 插件:Mypy 付出了很多努力来提高对 NumPy 等库的理解。您可能希望研究提供更好支持的第三方插件或类型存根,尽管它们仍在开发中。

    • -1

相关问题

  • 如何将 for 循环拆分为 3 个单独的数据框?

  • 如何检查 Pandas DataFrame 中的所有浮点列是否近似相等或接近

  • “load_dataset”如何工作,因为它没有检测示例文件?

  • 为什么 pandas.eval() 字符串比较返回 False

  • Python tkinter/ ttkboostrap dateentry 在只读状态下不起作用

Sidebar

Stats

  • 问题 205573
  • 回答 270741
  • 最佳答案 135370
  • 用户 68524
  • 热门
  • 回答
  • Marko Smith

    Vue 3:创建时出错“预期标识符但发现‘导入’”[重复]

    • 1 个回答
  • Marko Smith

    为什么这个简单而小的 Java 代码在所有 Graal JVM 上的运行速度都快 30 倍,但在任何 Oracle JVM 上却不行?

    • 1 个回答
  • Marko Smith

    具有指定基础类型但没有枚举器的“枚举类”的用途是什么?

    • 1 个回答
  • Marko Smith

    如何修复未手动导入的模块的 MODULE_NOT_FOUND 错误?

    • 6 个回答
  • Marko Smith

    `(表达式,左值) = 右值` 在 C 或 C++ 中是有效的赋值吗?为什么有些编译器会接受/拒绝它?

    • 3 个回答
  • Marko Smith

    何时应使用 std::inplace_vector 而不是 std::vector?

    • 3 个回答
  • Marko Smith

    在 C++ 中,一个不执行任何操作的空程序需要 204KB 的堆,但在 C 中则不需要

    • 1 个回答
  • Marko Smith

    PowerBI 目前与 BigQuery 不兼容:Simba 驱动程序与 Windows 更新有关

    • 2 个回答
  • Marko Smith

    AdMob:MobileAds.initialize() - 对于某些设备,“java.lang.Integer 无法转换为 java.lang.String”

    • 1 个回答
  • Marko Smith

    我正在尝试仅使用海龟随机和数学模块来制作吃豆人游戏

    • 1 个回答
  • Martin Hope
    Aleksandr Dubinsky 为什么 InetAddress 上的 switch 模式匹配会失败,并出现“未涵盖所有可能的输入值”? 2024-12-23 06:56:21 +0800 CST
  • Martin Hope
    Phillip Borge 为什么这个简单而小的 Java 代码在所有 Graal JVM 上的运行速度都快 30 倍,但在任何 Oracle JVM 上却不行? 2024-12-12 20:46:46 +0800 CST
  • Martin Hope
    Oodini 具有指定基础类型但没有枚举器的“枚举类”的用途是什么? 2024-12-12 06:27:11 +0800 CST
  • Martin Hope
    sleeptightAnsiC `(表达式,左值) = 右值` 在 C 或 C++ 中是有效的赋值吗?为什么有些编译器会接受/拒绝它? 2024-11-09 07:18:53 +0800 CST
  • Martin Hope
    The Mad Gamer 何时应使用 std::inplace_vector 而不是 std::vector? 2024-10-29 23:01:00 +0800 CST
  • Martin Hope
    Chad Feller 在 5.2 版中,bash 条件语句中的 [[ .. ]] 中的分号现在是可选的吗? 2024-10-21 05:50:33 +0800 CST
  • Martin Hope
    Wrench 为什么双破折号 (--) 会导致此 MariaDB 子句评估为 true? 2024-05-05 13:37:20 +0800 CST
  • Martin Hope
    Waket Zheng 为什么 `dict(id=1, **{'id': 2})` 有时会引发 `KeyError: 'id'` 而不是 TypeError? 2024-05-04 14:19:19 +0800 CST
  • Martin Hope
    user924 AdMob:MobileAds.initialize() - 对于某些设备,“java.lang.Integer 无法转换为 java.lang.String” 2024-03-20 03:12:31 +0800 CST
  • Martin Hope
    MarkB 为什么 GCC 生成有条件执行 SIMD 实现的代码? 2024-02-17 06:17:14 +0800 CST

热门标签

python javascript c++ c# java typescript sql reactjs html

Explore

  • 主页
  • 问题
    • 最新
    • 热门
  • 标签
  • 帮助

Footer

AskOverflow.Dev

关于我们

  • 关于我们
  • 联系我们

Legal Stuff

  • Privacy Policy

Language

  • Pt
  • Server
  • Unix

© 2023 AskOverflow.DEV All Rights Reserve