考虑以下最小示例:
from array import array
def foo(arr: array) -> None:
print(arr)
Run Code Online (Sandbox Code Playgroud)
我有一个带有参数的函数array。我的项目是静态类型的并使用mypy。Mypy 抱怨说:
Mypy: Missing type parameters for generic type "array".
你能帮我理解我应该如何输入提示参数吗?我似乎找不到有关该主题的文档。我不明白为什么 mypy 会认为这是一个通用类型。
为了澄清,根据我的理解,我使用的类型提示有效,但 mypy 仍然抱怨,因为它认为它是通用类型,并且想要“元素”的类型。我是否遗漏了什么,或者是 mypy 中的错误?
与此相关: 数组的类型提示是什么?
我时不时地发现自己定义一个带有参数的函数,该参数可以是类型的单个实例,也可以是同一类型的序列。当类型本身已经很复杂时,类型提示可能很快就会变得模糊。
而不是类似的东西
my_dicts: Union[Dict[str, int], Sequence[Dict[str, int]]]
Run Code Online (Sandbox Code Playgroud)
我想定义一个快捷方式,这样我就可以输入
my_dicts: SingleOrSequence[Dict[str, int]]
Run Code Online (Sandbox Code Playgroud)
我该如何以最Pythonic的方式解决这个问题?另请记住,为了与其他类型保持一致,调用签名应类似于上面的内容,即指定自定义类型名称并直接用方括号传递包含的类型。
我能想到的最好的看起来像这样:
import typing
class SingleOrSequenceClass():
@staticmethod
def __getitem__(typ):
return typing.Union[typ, typing.Sequence[typ]]
SingleOrSequence = SingleOrSequenceClass()
Run Code Online (Sandbox Code Playgroud)
这确实有效,但特别是必须实例化 SingleOrSequenceClass 并不适合我。关于如何改进这一点有什么建议吗?打字模块本身是否为此提供了任何优雅的解决方案?
我最近收到了这个很好的答案,用于以下方面:
from typing import Union, cast
class Default:
"""Placeholder for default arguments."""
# ham[] is mutable. `None` has meaning (or is not preferred).
def spam(ham: Union[list[str], None, type[Default]] = Default):
if ham is Default:
ham = ['prosciutto', 'jamon']
#ham = cast(Union[list[str], None], ham)
#assert isinstance(ham, (list, type(None)))
if ham is None:
print('Eggs?')
else:
print(str(len(ham)) + ' ham(s).')
Run Code Online (Sandbox Code Playgroud)
mypy错误:
Failed (exit code: 1) (2655 ms)
main.py:17: error: Argument 1 to "len" has incompatible type "Union[List[str], Type[Default]]"; expected "Sized" …Run Code Online (Sandbox Code Playgroud) 我们的代码中有一个典型的数据转换模式:当值为 None 时,我们让它通过。例如,
def capitalize(value):
if value is None:
return None
return value.capitalize()
# usage example:
assert capitalize(None) is None
assert capitalize("hello world") == "Hello world"
Run Code Online (Sandbox Code Playgroud)
我可以这样注释它:
from typing import Optional
def capitalize(value: Optional[str]) -> Optional[str]:
if value is None:
return None
return value.capitalize()
Run Code Online (Sandbox Code Playgroud)
看起来不错,但是下面的代码
capitalize("Hello world").split()
Run Code Online (Sandbox Code Playgroud)
总是会让mypy抱怨。
error: Item "None" of "Optional[str]" has no attribute "split"
Run Code Online (Sandbox Code Playgroud)
有没有办法用类型注解来表达“None总是转换为None,str总是转换为str”的转换规则?
有什么方法可以将 Numpy 数组键入为通用数组吗?
我目前正在使用 Numpy 1.23.5 和 Python 3.10,并且无法输入以下示例的提示。
import numpy as np
import numpy.typing as npt
E = TypeVar("E") # Should be bounded to a numpy type
def double_arr(arr: npt.NDArray[E]) -> npt.NDArray[E]:
return arr * 2
Run Code Online (Sandbox Code Playgroud)
我的期望是什么
arr = np.array([1, 2, 3], dtype=np.int8)
double_arr(arr) # npt.NDAarray[np.int8]
arr = np.array([1, 2.3, 3], dtype=np.float32)
double_arr(arr) # npt.NDAarray[np.float32]
Run Code Online (Sandbox Code Playgroud)
但我最终遇到以下错误
arr: npt.NDArray[E]
^^^
Could not specialize type "NDArray[ScalarType@NDArray]"
Type "E@double_arr" cannot be assigned to type "generic"
"object*" is incompatible with "generic"
Run Code Online (Sandbox Code Playgroud)
如果我将 E …
假设我的类型定义为:
data_type1 = list[str]
data_type2 = set[int]
Run Code Online (Sandbox Code Playgroud)
等等,如何通过分析这两种数据类型来获取主要类型(例如列表或集合)?
我试过:
issubclass(data_type1, list)
issubclass(data_type2, set)
Run Code Online (Sandbox Code Playgroud)
但它返回 False
任何想法?
我有一个类型T,namedtuple实际上是:
from collections import namedtuple
T = namedtuple('T', ('a', 'b'))
Run Code Online (Sandbox Code Playgroud)
list[T | None]我有一个接受 a和列表的函数:
def func(arg: list[T | None]):
...
l = [T(1, 2), T(2, 3)]
func(l) # Pylance error
Run Code Online (Sandbox Code Playgroud)
l属于 类型list[T]。
当我将 a 传递l给函数时,我从 Pylance 收到错误,指出 a 与list[T]不兼容,list[T | None]因为T cannot be assigned to T | None.
除了手动指定 mylist[T]实际上是 a之外list[T | None],我还能做些什么来使其正常工作而不出错?当然,在运行时一切都会按预期运行。
我正在尝试定义一个列表str作为函数参数的类型,但我不知道如何做到这一点
我知道 python 允许您定义函数来指定函数参数期望的值类型。例子:
def f(param: str):
print(type(param))
Run Code Online (Sandbox Code Playgroud)
但我不知道这个注释是如何调用的param: str,因此很难找到这方面的文档。据我了解,这只是代码文档中的美观,而不是参数的某种类型强制。
您能帮助我定义str该注释的列表和名称吗?
对于我想要的TypeScript的更清晰示例,可以这样写
function func(param: string[]) {}
Run Code Online (Sandbox Code Playgroud) 我正在尝试通过安装 pip
sudo -H python -m pip install -U pip
Run Code Online (Sandbox Code Playgroud)
但这会导致以下错误。
Traceback (most recent call last):
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/runpy.py", line 163, in _run_module_as_main
mod_name, _Error)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/runpy.py", line 111, in _get_module_details
__import__(mod_name) # Do not catch exceptions initializing package
File "/Library/Python/2.7/site-packages/pip-21.1.2-py2.7.egg/pip/__init__.py", line 1, in <module>
from typing import List, Optional
ImportError: No module named typing
Run Code Online (Sandbox Code Playgroud) 我对 Python 相当陌生,来自 Java 背景。我有这样的事情:
class A:
def __init__(self):
self.var1 = 1
self.var2 = 2
class B:
def __init__(self):
self.my_list = []
def add(self, a_object):
self.my_list.append(a_object)
def show(self):
for a_object in self.my_list:
print(a_object.var1, a_object.var2)
Run Code Online (Sandbox Code Playgroud)
现在,我知道这段代码会运行,但我的问题是,是否有任何方法可以在show方法中指定该a_object变量实际上是类型 A 的对象(例如类型转换 - 我会在 java 中编写类似的东西(A)a_object)。我首先希望这样做是为了提高代码的可读性以及自动完成功能。我猜想另一个解决方案是输入列表,如果可能的话,我也是好奇的。
谢谢你。
python ×10
python-typing ×10
type-hinting ×6
mypy ×4
python-3.x ×2
arrays ×1
list ×1
numpy ×1
pip ×1
pylance ×1
python-2.x ×1
python-3.9 ×1