我有以下代码a.py:
class Tags(enum.Flag):
NONE = 0
A = enum.auto()
B = enum.auto()
C = enum.auto()
# Allow using tags.A instead of tags.Tags.A
globals().update(Tags.__members__)
Run Code Online (Sandbox Code Playgroud)
但是当我在其他文件上使用它时, mypy (正确地)无法识别属性:
import tags
print(tags.A) # Module has no attribute "A"
Run Code Online (Sandbox Code Playgroud)
Python 3.6 有没有可能绕过这个问题?
已知的解决方案(对于我的情况来说不够好):
# type: ignore每次使用时都使用tags.Atags.Tags.A__getitem__在模块级别使用(仅适用于 Python 3.7)以下示例的类型提示应该是什么:
import plotly.graph_objs as go
def update_scene_callback():
....
def scatter_plot(input_data, layout):
fig = go.FigureWidget(input_data)
fig.update_layout(object_layout)
scatter = fig.data[0]
scatter.on_click(update_scene_callback)
return fig
Run Code Online (Sandbox Code Playgroud)
type(fig)函数plotly.graph_objs._figurewidget.FigureWidget
的输入和输出的类型应该是什么scatter_plot?
另外,假设我有一个数据帧作为函数的输入变量。但我不希望在函数内部更改数据框。有什么方法可以为输入变量分配类型,以便我们可以确保该变量不会在函数内部更改?
我是 Python 静态类型模块的新手mypy。我试图将整数和浮点数附加到一个数组中,我静态地将其输入为 Real。但mypy说它们是与 Real 不兼容的类型。我认为整数和浮点数是实数的子类型?
from typing import List
from numbers import Real
data : List[Real] = []
with open(path, 'r') as file:
for line in file:
line = line.strip()
if subject == 'time':
data.append(float(line))
else:
data.append(int(line))
Run Code Online (Sandbox Code Playgroud)
错误信息:
from typing import List
from numbers import Real
data : List[Real] = []
with open(path, 'r') as file:
for line in file:
line = line.strip()
if subject == 'time':
data.append(float(line))
else:
data.append(int(line))
Run Code Online (Sandbox Code Playgroud) 我正在使用pydantic并想要创建包含 pandas 数据帧的类。我在网上找了很长一段时间,但没有找到任何东西。我的自定义类型代码如下所示。我将数据帧的类型命名为 pd.DataFrame 但显然它不正确。有谁知道如何声明 pandas 数据框类型?
import pandas as pd
from pydantic import BaseModel
class SubModelInput(BaseModel):
a: pd.DataFrame
b: pd.DataFrame
class ModelInput(BaseModel):
SubModelInput: SubModelInput
a: pd.DataFrame
b: pd.DataFrame
c: pd.DataFrame
Run Code Online (Sandbox Code Playgroud)
谢谢你的帮助!
想象一下,我们有一些巨大的遗留代码库,其中有很多文件被忽略了 Mypy 警告:
\ndef foobar():\n x = some_external_class.some_method()[0] # type: ignore[ignore-some-mypy-warning]\nRun Code Online (Sandbox Code Playgroud)\n该走了...
\n代码的某些部分已更改。代码的某些部分仍然是相同的。如何检查每个“忽略”评论以了解:如果删除它,我会收到错误吗?
\n期望的输出:
\ndef foobar():\n x = some_external_class.some_method()[0] # type: ignore[ignore-some-mypy-warning]\nRun Code Online (Sandbox Code Playgroud)\n有没有现有的工具可以实现这一目标?关于自定义脚本有什么想法吗?
\n我唯一的想法是:
\n源代码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 Code Online (Sandbox Code Playgroud)
运行 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 …Run Code Online (Sandbox Code Playgroud) 我知道在Python中OpenCV图像是numpy数组,对应于c++中的cv::Mat。
这个问题是关于在 python 函数中放入什么类型提示来正确限制 OpenCV 图像(甚至可能对于特定类型的 OpenCV 图像)。
我现在做的是:
import numpy as np
import cv2
Mat = np.ndarray
def my_fun(image: Mat):
cv2.imshow('display', image)
cv2.waitKey()
Run Code Online (Sandbox Code Playgroud)
有没有更好的方法在 python 中为 OpenCV 图像添加输入信息?
我的印象是typingPython 中的模块主要是为了提高代码可读性和代码文档目的。
在玩过它并阅读了有关该模块的内容之后,我设法让自己对它感到困惑。
即使这两个变量未初始化(就像您通常初始化它们一样,例如a = "test"),下面的代码也可以工作。
我只在上面添加了类型提示,一切看起来都很好。也就是说,我没有得到 a ,就像我在代码中NameError得到的那样aNameError: name 'a' is not defined
以这种方式声明变量(带有类型提示)是一种好的做法吗?为什么这有效?
from typing import Any
test_var: int
a: Any
print('hi')
Run Code Online (Sandbox Code Playgroud)
我期望test_var: int返回一个错误,指出该错误test_var尚未启动,并且我必须执行类似的操作test_var: int = 0(或任何值)。是否因为我向其中添加了类型提示而将其设置为默认值?
我有一个类变量,如下所示:
class MyClass:
def __init__(self):
self.value: MyOtherClass | None = None
self.initialize_value()
def initialize_value(self):
self.value = MyOtherClass()
def use_value(self):
return self.value.used
Run Code Online (Sandbox Code Playgroud)
self.valueMyOtherClass保证在使用之前被初始化为 的实例self.use_value();然而,它必须保持为None在构造函数中。这里的困境是如何正确地提示这种情况。
error: Item "None" of "Optional[MyOtherClass]" has no attribute "used" [union-attr]self.initialize_value(),我会得到一个Instance attribute value defined outside __init__从 Pylint 收到错误解决这个问题的最佳方法是什么?多谢!
考虑一个也用协议注释的 Python 协议属性。我发现在这种情况下,即使我的自定义数据类型遵循嵌套协议,mypy 和 Pyright 都会报告错误。例如,下面的代码Outer遵循协议,因为HasHasA它遵循协议。hasa: HasAInnerHasA
from dataclasses import dataclass
from typing import Protocol
class HasA(Protocol):
a: int
class HasHasA(Protocol):
hasa: HasA
@dataclass
class Inner:
a: int
@dataclass
class Outer:
hasa: Inner
def func(b: HasHasA): ...
o = Outer(Inner(0))
func(o)
Run Code Online (Sandbox Code Playgroud)
但是,mypy 显示以下错误。
nested_protocol.py:22: error: Argument 1 to "func" has incompatible type "Outer"; expected "HasHasA" [arg-type]
nested_protocol.py:22: note: Following member(s) of "Outer" have conflicts:
nested_protocol.py:22: note: hasa: expected "HasA", got "Inner"
Run Code Online (Sandbox Code Playgroud)
我的代码有什么问题吗?
python-typing ×10
python ×8
mypy ×5
python-3.x ×3
type-hinting ×3
numpy ×2
annotations ×1
dataframe ×1
opencv ×1
pandas ×1
plotly ×1
pydantic ×1
pyright ×1
python-3.6 ×1