如何键入提示功能与numpy兼容

发布于 2025-02-06 07:12:36 字数 1378 浏览 2 评论 0 原文

example.py 的源代码:

from typing import Union, Any
import numpy as np

Number = Union[int, float, np.floating[Any]]


def add_one(num: Number) -> Number:
    return num + 1


inputs = [1, 2, 3]
outputs = [add_one(n) for n in inputs]

avg = np.mean(outputs)

运行mypy:

mypy example.py
src/example.py:14: error: Argument 1 to "mean" has incompatible type "List[Union[float, floating[Any]]]"; expected "Union[_SupportsArray[dtype[Any]], _NestedSequence[_SupportsArray[dtype[Any]]], bool, int, float, complex, str, bytes, _NestedSequence[Union[bool, int, float, complex, str, bytes]]]"
Found 1 error in 1 file (checked 1 source file)

我可以将所有内容更改为 np.doploing [any] 解决了numpy问题代码> np.float32(...):

from typing import Any
import numpy as np


def add_one(num: np.floating[Any]) -> np.floating[Any]:
    return num + 1


inputs = [1, 2, 3]
outputs = [add_one(np.float32(n)) for n in inputs]

avg = np.mean(outputs)

是否有正确的方法键入 add_one 函数,以便其输出与numpy函数兼容,例如 np.mean 没有与python原始类型的兼容性?最终目标是能够这样使用:

inputs = [1, 2, 3]
outputs = [add_one(n) for n in inputs]
avg = np.mean(outputs)

Source code of example.py:

from typing import Union, Any
import numpy as np

Number = Union[int, float, np.floating[Any]]


def add_one(num: Number) -> Number:
    return num + 1


inputs = [1, 2, 3]
outputs = [add_one(n) for n in inputs]

avg = np.mean(outputs)

Run mypy:

mypy example.py
src/example.py:14: error: Argument 1 to "mean" has incompatible type "List[Union[float, floating[Any]]]"; expected "Union[_SupportsArray[dtype[Any]], _NestedSequence[_SupportsArray[dtype[Any]]], bool, int, float, complex, str, bytes, _NestedSequence[Union[bool, int, float, complex, str, bytes]]]"
Found 1 error in 1 file (checked 1 source file)

I can change everything to np.floating[Any] which fixes the numpy issue, but then I have to cast primitives to np.float32(...):

from typing import Any
import numpy as np


def add_one(num: np.floating[Any]) -> np.floating[Any]:
    return num + 1


inputs = [1, 2, 3]
outputs = [add_one(np.float32(n)) for n in inputs]

avg = np.mean(outputs)

Is there a correct way to type hint the add_one function so that its outputs are compatible with numpy functions such as np.mean without breaking compatibility with the python primitive types? The end goal is to be able to use it like this:

inputs = [1, 2, 3]
outputs = [add_one(n) for n in inputs]
avg = np.mean(outputs)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

一个人的夜不怕黑 2025-02-13 07:12:36

Mypy对复杂类型的层次结构过于严格。 (可能是由于 numpy.mean.mean 的第1 arg

。 ,只是一个林格错误,很难告诉谁应该归咎于谁。

您有几个选项:

1。只需忽略调用 earne

avg = avg = np.mean(outputs)#类型:ignore

a list list list 的 avg = avg = avg = avg = avg = avg = avg = avg = a a [t] 应该 array_like ,因为 numpy 可以处理它。但是由于某种原因, mypy 有时无法使自定义类型的等价 。代码是正确的,因此您可以只是忽略该调用的类型。


2。保持类型提示原样。使用 np.Array

altought mypy 未能识别 list [t] array_like 用于复杂和抽象类型<代码> t ,它不会抱怨 np.Array

以下编辑脚本在这两个变体中都可以正常工作,并且没有任何错误,也没有发出Mypy的警告:

from typing import Union, Any
import numpy as np

Number = Union[int, float, np.ndarray]

def add_one(num: Number) -> np.ndarray: 
    return np.array(num) + 1 #Using np.array


inputs = [1, 2, 3]
outputs = [add_one(n) for n in inputs] 

avg = np.mean(outputs)

print("Outputs:", outputs) # Outputs: [2, 3, 4]
print("Average:", avg) # Average: 3.0

运行: mypy 。

from typing import Union, Any
import numpy as np

Number = Union[int, float, np.floating[Any]]

def add_one(num: Number) -> Number:
    return num + 1


inputs = [1, 2, 3]
outputs = np.array([add_one(n) for n in inputs]) #Using np.array

avg = np.mean(outputs)

print("Outputs:", outputs) # Outputs: [2, 3, 4]
print("Average:", avg) # Average: 3.0

​在1个源文件中找到的问题

请注意,所有 numpys的示例 for sane pass np np。 Array 而不是 list 作为 a 属性


3。定义自定义协议支持Aritmethic和数字操作以及转换为原始类型和numpy类型

是一个好主意,确保它与其他数字类表现良好,我使用 number package real 类,因为它非常谨慎兼容,但您可以进一步限制它。


import numpy as np
from typing import Protocol, TypeVar, Union
from numbers import Number as Real

class Number(Protocol):
    # Arithmetic operations
    def __add__(self, other: Union[Real, "Number"]) -> "Number": ...
    def __radd__(self, other: Union[Real, "Number"]) -> "Number": ...
    def __sub__(self, other: Union[Real, "Number"]) -> "Number": ...
    def __rsub__(self, other: Union[Real, "Number"]) -> "Number": ...
    def __mul__(self, other: Union[Real, "Number"]) -> "Number": ...
    def __rmul__(self, other: Union[Real, "Number"]) -> "Number": ...
    def __truediv__(self, other: Union[Real, "Number"]) -> "Number": ...
    def __rtruediv__(self, other: Union[Real, "Number"]) -> "Number": ...
    def __floordiv__(self, other: Union[Real, "Number"]) -> "Number": ...
    def __rfloordiv__(self, other: Union[Real, "Number"]) -> "Number": ...
    def __mod__(self, other: Union[Real, "Number"]) -> "Number": ...
    def __rmod__(self, other: Union[Real, "Number"]) -> "Number": ...
    def __pow__(self, other: Union[Real, "Number"]) -> "Number": ...
    def __rpow__(self, other: Union[Real, "Number"]) -> "Number": ...

    # Unary operations
    def __neg__(self) -> "Number": ...
    def __pos__(self) -> "Number": ...
    def __abs__(self) -> "Number": ...

    # Other comparisons
    def __eq__(self, other: Union[Real, "Number"]) -> bool: ...
    def __ne__(self, other: Union[Real, "Number"]) -> bool: ...
    def __lt__(self, other: Union[Real, "Number"]) -> bool: ...
    def __le__(self, other: Union[Real, "Number"]) -> bool: ...
    def __gt__(self, other: Union[Real, "Number"]) -> bool: ...
    def __ge__(self, other: Union[Real, "Number"]) -> bool: ...

    # Conversions
    def __float__(self) -> float: ...
    def __int__(self) -> int: ...
    def __index__(self) -> int: ...

    # Implicit conversion to NumPy types
    def __array__(self) -> np.ndarray: ...
    def __array_ufunc__(self, ufunc, method, *inputs, **kwargs) -> np.ndarray: ...

N = TypeVar("N", bound=Number)

然后,您应该能够这样使用它:

def add_one(num: N) -> N: 
    return num + 1 

inputs = [1, 2, 3]
outputs = [add_one(n) for n in inputs] 

avg = np.mean(outputs)

print("Outputs:", outputs) # Outputs: [2, 3, 4]
print("Average:", avg) # Average: 3.0

运行: mypy ./example.py.py

输出:成功:1源文件中没有发现任何问题


4。定义自定义实现 list [number] 明确 array_like

替代方案,如果您正在运行python&gt; = 3.12,并且提供支持 pep 695 您可以定义一个列表实现 array 接口的子类型:

...
T = TypeVar("T", bound = Number)
class NArray[T] (list[T]):
    def __array__(self): return np.array(self)

...

outputs : NArray[Number]  = NArray([add_one(n) for n in inputs]) #Using NArray

运行: mypy ./example.py.py.py

输出:成功:1个源中未发现任何问题文件


说明

问题是列表的mypys处理[数字],而不是

按照 numpy的参考 numpy.mean.mean 定义为 numpy.mean.mean(a,axis = none,dype = none,none,none,out of = none,keepdims =&lt; no value&gt;, *,其中=&lt; no value&gt;)其中 a a 是类型 array_like

in numpy,numpy定义 array_like be:

array_like
任何 scalar 序列可以解释为ndarray。除了&gt; ndarrays和标量此类别包括列表(可能嵌套并具有不同的元素类型)和元组。 numpy.Array接受的任何参数是 array_like

您查看 numpy.core.fromnumeric.pyi 的重载函数的定义平均值您发现有6个实际的过载平均值


@overload
def mean(
    a: _ArrayLikeFloat_co,
    axis: None = ...,
    dtype: None = ...,
    out: None = ...,
    keepdims: Literal[False] = ...,
    *,
    where: _ArrayLikeBool_co = ...,
) -> floating[Any]: ...
@overload
def mean(
    a: _ArrayLikeComplex_co,
    axis: None = ...,
    dtype: None = ...,
    out: None = ...,
    keepdims: Literal[False] = ...,
    *,
    where: _ArrayLikeBool_co = ...,
) -> complexfloating[Any, Any]: ...
@overload
def mean(
    a: _ArrayLikeComplex_co | _ArrayLikeObject_co,
    axis: None | _ShapeLike = ...,
    dtype: None = ...,
    out: None = ...,
    keepdims: bool = ...,
    *,
    where: _ArrayLikeBool_co = ...,
) -> Any: ...
@overload
def mean(
    a: _ArrayLikeComplex_co | _ArrayLikeObject_co,
    axis: None = ...,
    dtype: _DTypeLike[_SCT] = ...,
    out: None = ...,
    keepdims: Literal[False] = ...,
    *,
    where: _ArrayLikeBool_co = ...,
) -> _SCT: ...
@overload
def mean(
    a: _ArrayLikeComplex_co | _ArrayLikeObject_co,
    axis: None | _ShapeLike = ...,
    dtype: DTypeLike = ...,
    out: None = ...,
    keepdims: bool = ...,
    *,
    where: _ArrayLikeBool_co = ...,
) -> Any: ...
@overload
def mean(
    a: _ArrayLikeComplex_co | _ArrayLikeObject_co,
    axis: None | _ShapeLike = ...,
    dtype: DTypeLike = ...,
    out: _ArrayType = ...,
    keepdims: bool = ...,
    *,
    where: _ArrayLikeBool_co = ...,
) -> _ArrayType: ...

那么...什么给? list [number] 应该与 array_like 兼容,对吗?

好吧,让我们仔细观察Mypy给出的错误:

error: Argument 1 to "mean" has incompatible type "list[int | float | floating[Any]]"; expected "_SupportsArray[dtype[bool_ | integer[Any] | floating[Any]]] | _NestedSequence[_SupportsArray[dtype[bool_ | integer[Any] | floating[Any]]]] | bool | int | float | _NestedSequence[bool | int | float]"  [arg-type]

您会注意到,尽管它显然是引用了晦涩的抽象类型的结合(也可能是自动生成的类型),联盟中的主要类型是 _supportArray ,这是一个非常抽象的协议 numpy._typing._array_like 中定义的:

# The `_SupportsArray` protocol only cares about the default dtype
# (i.e. `dtype=None` or no `dtype` parameter at all) of the to-be returned
# array.
# Concrete implementations of the protocol are responsible for adding
# any and all remaining overloads
@runtime_checkable
class _SupportsArray(Protocol[_DType_co]):
    def __array__(self) -> ndarray[Any, _DType_co]: ...

我们要寻找的目标应该是:

_SupportsArray[dtype[bool_ | integer[Any] | floating[Any]]]

€this是问题! linter期望 _supportSarray bool _ integer [any] floing> floating [any]

如果 >数字其中 union [bool_ |整数[任何] |浮动[任何] ,mypy不会抱怨。

但是这是当前实现numpy 的错误,预期类型应为 _supportSarray [任何] 作为文档所述。

MyPy is beeing too strict on complex type hierarchy. (possibly due to an ill-defined type for numpy.mean's 1st arg.) (( maybe a bug in MyPy's stubs/type definitions?))

The code runs, is just a linter error, hard to tell who's to blame.

You have a few options:

1. Just ignore typecheck for the call to mean

avg = np.mean(outputs) # type: ignore

A List[T] should be an array_like, as NumPy can handle it. But for some reason MyPy sometimes fails to make that equivalence for custom types. The code is correct, so you could just ignore types for that call.


2. Keep type hint as-is. Use np.array

Altought MyPy fails to recognize that List[T] is array_like for complex and abstract types T, it won't complain about an np.array

The following edited script works fine in both variations, and gives no errors nor warnings from MyPy:

from typing import Union, Any
import numpy as np

Number = Union[int, float, np.ndarray]

def add_one(num: Number) -> np.ndarray: 
    return np.array(num) + 1 #Using np.array


inputs = [1, 2, 3]
outputs = [add_one(n) for n in inputs] 

avg = np.mean(outputs)

print("Outputs:", outputs) # Outputs: [2, 3, 4]
print("Average:", avg) # Average: 3.0

Running: mypy ./example.py

Output: Success: no issues found in 1 source file

from typing import Union, Any
import numpy as np

Number = Union[int, float, np.floating[Any]]

def add_one(num: Number) -> Number:
    return num + 1


inputs = [1, 2, 3]
outputs = np.array([add_one(n) for n in inputs]) #Using np.array

avg = np.mean(outputs)

print("Outputs:", outputs) # Outputs: [2, 3, 4]
print("Average:", avg) # Average: 3.0

Running: mypy ./example.py

Output: Success: no issues found in 1 source file

Note that all of Numpys's examples for mean pass np.array and not List as a attribute


3. Define custom Protocol that supports aritmethic and numerical operations and conversion to primitive types and Numpy types

It'd be a good idea to ensure it behaves well with other number classes, I've used number package's Real class, as it is very braodly compatible, but you could further constrian it.


import numpy as np
from typing import Protocol, TypeVar, Union
from numbers import Number as Real

class Number(Protocol):
    # Arithmetic operations
    def __add__(self, other: Union[Real, "Number"]) -> "Number": ...
    def __radd__(self, other: Union[Real, "Number"]) -> "Number": ...
    def __sub__(self, other: Union[Real, "Number"]) -> "Number": ...
    def __rsub__(self, other: Union[Real, "Number"]) -> "Number": ...
    def __mul__(self, other: Union[Real, "Number"]) -> "Number": ...
    def __rmul__(self, other: Union[Real, "Number"]) -> "Number": ...
    def __truediv__(self, other: Union[Real, "Number"]) -> "Number": ...
    def __rtruediv__(self, other: Union[Real, "Number"]) -> "Number": ...
    def __floordiv__(self, other: Union[Real, "Number"]) -> "Number": ...
    def __rfloordiv__(self, other: Union[Real, "Number"]) -> "Number": ...
    def __mod__(self, other: Union[Real, "Number"]) -> "Number": ...
    def __rmod__(self, other: Union[Real, "Number"]) -> "Number": ...
    def __pow__(self, other: Union[Real, "Number"]) -> "Number": ...
    def __rpow__(self, other: Union[Real, "Number"]) -> "Number": ...

    # Unary operations
    def __neg__(self) -> "Number": ...
    def __pos__(self) -> "Number": ...
    def __abs__(self) -> "Number": ...

    # Other comparisons
    def __eq__(self, other: Union[Real, "Number"]) -> bool: ...
    def __ne__(self, other: Union[Real, "Number"]) -> bool: ...
    def __lt__(self, other: Union[Real, "Number"]) -> bool: ...
    def __le__(self, other: Union[Real, "Number"]) -> bool: ...
    def __gt__(self, other: Union[Real, "Number"]) -> bool: ...
    def __ge__(self, other: Union[Real, "Number"]) -> bool: ...

    # Conversions
    def __float__(self) -> float: ...
    def __int__(self) -> int: ...
    def __index__(self) -> int: ...

    # Implicit conversion to NumPy types
    def __array__(self) -> np.ndarray: ...
    def __array_ufunc__(self, ufunc, method, *inputs, **kwargs) -> np.ndarray: ...

N = TypeVar("N", bound=Number)

Then you should be able to use it like this:

def add_one(num: N) -> N: 
    return num + 1 

inputs = [1, 2, 3]
outputs = [add_one(n) for n in inputs] 

avg = np.mean(outputs)

print("Outputs:", outputs) # Outputs: [2, 3, 4]
print("Average:", avg) # Average: 3.0

Running: mypy ./example.py

Output: Success: no issues found in 1 source file


4. Define custom implementation of List[Number] that is explicitly array_like.

Alternative, if you're running Python >= 3.12, and MyPy >= 1.12 which offers support for PEP 695 you could define a list subtype that implements the array interface:

...
T = TypeVar("T", bound = Number)
class NArray[T] (list[T]):
    def __array__(self): return np.array(self)

...

outputs : NArray[Number]  = NArray([add_one(n) for n in inputs]) #Using NArray

Running: mypy ./example.py

Output: Success: no issues found in 1 source file


Explanation

The problem is MyPys handling of the List[Number], not the underlying types contained in it

As per Numpy's reference numpy.mean is defined as numpy.mean(a, axis=None, dtype=None, out=None, keepdims=<no value>, *, where=<no value>) where a is of type array_like

In it's glossary, Numpy defines array_like to be:

array_like
Any scalar or sequence that can be interpreted as an ndarray. In addition to > ndarrays and scalars this category includes lists (possibly nested and with different element types) and tuples. Any argument accepted by numpy.array is array_like.

And

When you look at the numpy.core.fromnumeric.pyi's definitions for overloaded function mean you find that there are 6 actual overloads of mean:


@overload
def mean(
    a: _ArrayLikeFloat_co,
    axis: None = ...,
    dtype: None = ...,
    out: None = ...,
    keepdims: Literal[False] = ...,
    *,
    where: _ArrayLikeBool_co = ...,
) -> floating[Any]: ...
@overload
def mean(
    a: _ArrayLikeComplex_co,
    axis: None = ...,
    dtype: None = ...,
    out: None = ...,
    keepdims: Literal[False] = ...,
    *,
    where: _ArrayLikeBool_co = ...,
) -> complexfloating[Any, Any]: ...
@overload
def mean(
    a: _ArrayLikeComplex_co | _ArrayLikeObject_co,
    axis: None | _ShapeLike = ...,
    dtype: None = ...,
    out: None = ...,
    keepdims: bool = ...,
    *,
    where: _ArrayLikeBool_co = ...,
) -> Any: ...
@overload
def mean(
    a: _ArrayLikeComplex_co | _ArrayLikeObject_co,
    axis: None = ...,
    dtype: _DTypeLike[_SCT] = ...,
    out: None = ...,
    keepdims: Literal[False] = ...,
    *,
    where: _ArrayLikeBool_co = ...,
) -> _SCT: ...
@overload
def mean(
    a: _ArrayLikeComplex_co | _ArrayLikeObject_co,
    axis: None | _ShapeLike = ...,
    dtype: DTypeLike = ...,
    out: None = ...,
    keepdims: bool = ...,
    *,
    where: _ArrayLikeBool_co = ...,
) -> Any: ...
@overload
def mean(
    a: _ArrayLikeComplex_co | _ArrayLikeObject_co,
    axis: None | _ShapeLike = ...,
    dtype: DTypeLike = ...,
    out: _ArrayType = ...,
    keepdims: bool = ...,
    *,
    where: _ArrayLikeBool_co = ...,
) -> _ArrayType: ...

So... what gives? List[Number] should be compatible with array_like, right?

Well, let's look closely at the error MyPy gives:

error: Argument 1 to "mean" has incompatible type "list[int | float | floating[Any]]"; expected "_SupportsArray[dtype[bool_ | integer[Any] | floating[Any]]] | _NestedSequence[_SupportsArray[dtype[bool_ | integer[Any] | floating[Any]]]] | bool | int | float | _NestedSequence[bool | int | float]"  [arg-type]

You'll notice that althought it's clearly referincing a Union of obscure abstract types (and possibly auto-generated types as well) the primary type in the Union is _SupportsArray, which is a pretty abstract protocol defined in numpy._typing._array_like:

# The `_SupportsArray` protocol only cares about the default dtype
# (i.e. `dtype=None` or no `dtype` parameter at all) of the to-be returned
# array.
# Concrete implementations of the protocol are responsible for adding
# any and all remaining overloads
@runtime_checkable
class _SupportsArray(Protocol[_DType_co]):
    def __array__(self) -> ndarray[Any, _DType_co]: ...

The target we're looking for should be:

_SupportsArray[dtype[bool_ | integer[Any] | floating[Any]]]

¡That's the problem! linter expects a _SupportsArray of bool_, integer[Any], or floating[Any]

If Number where Union[bool_ | integer[Any] | floating[Any], MyPy wouldn't complain.

But that's a bug in current implementation of NumPy, the expected type should be _SupportsArray[Any] as the documentation states.

何止钟意 2025-02-13 07:12:36

在确保最大灵活性的同时,解决此 mypy 问题的一种更强大的方法是使用python的协议键入 ,它允许更精确的类型提示值支持数值操作。

您可以定义自定义 supportsnumericOps 协议

from typing import Protocol, TypeVar
import numpy as np

class SupportsNumericOps(Protocol):
    """A protocol that ensures objects support basic numeric operations."""
    def __add__(self, other: float) -> float: ...
    def __radd__(self, other: float) -> float: ...
    def __float__(self) -> float: ...

T = TypeVar("T", bound=SupportsNumericOps)

def add_one(num: T) -> float:
    """Ensure compatibility with both Python numbers and NumPy types."""
    return float(num) + 1  # Explicit float conversion

def process_numbers(nums: list[T]) -> float:
    """Process numbers in a type-safe way and compute the mean."""
    outputs = [add_one(n) for n in nums]
    return np.mean(outputs)  # ✅ No MyPy error

# Example usage
inputs = [1, 2, 3]
avg = process_numbers(inputs)  # Works without MyPy errors

A more robust way to solve this MyPy issue while ensuring maximum flexibility is to use Python’s Protocol from typing, which allows for more precise type hinting for values that support numerical operations.

You can define a Custom SupportsNumericOps Protocol

from typing import Protocol, TypeVar
import numpy as np

class SupportsNumericOps(Protocol):
    """A protocol that ensures objects support basic numeric operations."""
    def __add__(self, other: float) -> float: ...
    def __radd__(self, other: float) -> float: ...
    def __float__(self) -> float: ...

T = TypeVar("T", bound=SupportsNumericOps)

def add_one(num: T) -> float:
    """Ensure compatibility with both Python numbers and NumPy types."""
    return float(num) + 1  # Explicit float conversion

def process_numbers(nums: list[T]) -> float:
    """Process numbers in a type-safe way and compute the mean."""
    outputs = [add_one(n) for n in nums]
    return np.mean(outputs)  # ✅ No MyPy error

# Example usage
inputs = [1, 2, 3]
avg = process_numbers(inputs)  # Works without MyPy errors
顾北清歌寒 2025-02-13 07:12:36

出现问题是因为 np.mean 期望输入与 numpy 数组兼容,但是当您使用时, add_one 函数返回混合类型。联合[int,float,np。

您还将返回类型设置为数字,这可能不是输入此功能的最精确或最有用的方法,尤其是在使用Numpy时。

我认为,与 numpy 函数兼容键入提示的最准确方法是使用 np.ndarray dtype 参数覆盖该参数,该参数涵盖预期数字类型。

示例代码:

import numpy as np
from typing import Union

Number = Union[int, float, np.ndarray]

def add_one(num: Number) -> np.ndarray:
    """Adds one to a number or each element in a NumPy array."""
    return np.array(num) + 1 

inputs = [1, 2, 3]
outputs = [add_one(n) for n in inputs] 

avg = np.mean(outputs)

print("Outputs:", outputs)
print("Average:", avg)

输出:

Outputs: [2, 3, 4]
Average: 3.0

The problem arises because np.mean expects inputs to be compatible with NumPy arrays, but the add_one function returns mixed types when you use Union[int, float, np.floating[Any]].

You also set the return type to Number which might not be the most precise or helpful way to type hint this function, especially when working with NumPy.

In my opinion, the most accurate way to type hints for compatibility with NumPy functions is to use np.ndarray with a dtype argument that covers the expected numeric types.

Example Code:

import numpy as np
from typing import Union

Number = Union[int, float, np.ndarray]

def add_one(num: Number) -> np.ndarray:
    """Adds one to a number or each element in a NumPy array."""
    return np.array(num) + 1 

inputs = [1, 2, 3]
outputs = [add_one(n) for n in inputs] 

avg = np.mean(outputs)

print("Outputs:", outputs)
print("Average:", avg)

Output:

Outputs: [2, 3, 4]
Average: 3.0
一江春梦 2025-02-13 07:12:36

只需使用 number = union [int,float] 不会丢下任何mypy错误。

Just using Number = Union[int, float] doesn't throw any mypy error.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文