问题是这样的:
class A():
def foo() -> B:
pass
class B():
def bar() -> A:
pass
Run Code Online (Sandbox Code Playgroud)
这将引发一个NameError: name 'B' is not defined.
为了进行类型检查,我不愿意更改-> B为-> "B". 有什么解决方法吗?
以下代码mypy按预期被拒绝:
def foo(value: int) -> None:
print(value, type(value))
foo(None)
Run Code Online (Sandbox Code Playgroud)
输出:
error: Argument 1 to "foo" has incompatible type "None"; expected "int"
Run Code Online (Sandbox Code Playgroud)
但是在引入了一个默认参数之后None,就没有错误了:
def foo(value: int=None) -> None:
print(value, type(value))
foo(None)
Run Code Online (Sandbox Code Playgroud)
如果我们从to更改,我希望mypy只允许None(作为参数和默认值),但似乎不需要这样做。为什么?valueintOptional[int]
假设我有一些代码
def get_x(d: dict) -> int:
d["x"]
Run Code Online (Sandbox Code Playgroud)
但是,我想告诉 mypyd应该只包含某些键(例如只有“x”键)。这样,如果我在尝试引用无效键的代码中犯了错误d,mypy 将触发错误。
我的问题是:
我想为我的 SQLAlchemy 基类使用类型,但似乎找不到类型定义。
例如:
from sqlalchemy.types import BigInteger
from sqlalchemy.schema import Column, Index
from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base()
class User(Base):
__tablename__ = "users"
id_user = Column(
BigInteger, primary_key=True, autoincrement=True, nullable=False, index=True
)
username = Column(String, unique=True, index=True)
Run Code Online (Sandbox Code Playgroud)
现在,当引用这个 User 类时,我不知道该使用什么类型。此外,如果我想要一个包含 table_name 的字典:模型映射如下:
from typing import Any, Dict
table_model_map: Dict[str, Any] = {
"users": User,
"another_table": AnotherTableModel,
}
Run Code Online (Sandbox Code Playgroud)
我将如何定义这个字典的类型
非常感谢您帮助我理解这一点!
我很困惑为什么不像上面两个FooBar.__mro__那样显示<class '__main__.Parent'>。
在深入研究 CPython 源代码后,我仍然不知道为什么。
from typing import NamedTuple
from collections import namedtuple
A = namedtuple('A', ['test'])
class B(NamedTuple):
test: str
class Parent:
pass
class Foo(Parent, A):
pass
class Bar(Parent, B):
pass
class FooBar(Parent, NamedTuple):
pass
print(Foo.__mro__)
# prints (<class '__main__.Foo'>, <class '__main__.Parent'>, <class '__main__.A'>, <class 'tuple'>, <class 'object'>)
print(Bar.__mro__)
# prints (<class '__main__.Bar'>, <class '__main__.Parent'>, <class '__main__.B'>, <class 'tuple'>, <class 'object'>)
print(FooBar.__mro__)
# prints (<class '__main__.FooBar'>, <class 'tuple'>, <class 'object'>)
# expecting: (<class '__main__.FooBar'>, <class …Run Code Online (Sandbox Code Playgroud) 我有以下代码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 abc
import attr
@attr.s(auto_attribs=True)
class BaseConfig(abc.ABC):
option_base: str
@attr.s(auto_attribs=True)
class ConfigA(BaseConfig):
option_a: str
@attr.s(auto_attribs=True)
class ConfigB(BaseConfig):
option_b: bool
class Base(abc.ABC):
@abc.abstractmethod
def do_something(self, config: BaseConfig):
pass
class ClassA(Base):
def do_something(self, config: ConfigA):
# test.py:27: error: Argument 1 of "do_something" is incompatible with supertype "Base"; supertype defines the argument type as "BaseConfig"
print("option_a: " + config.option_a)
class ClassB(Base):
def do_something(self, config: ConfigB):
# test.py:33: error: Argument 1 of "do_something" is incompatible with supertype "Base"; supertype defines the argument …Run Code Online (Sandbox Code Playgroud) 我想创建一个类型注释来描述必须是 class和 classT的子类的类型。AB
T = TypeVar('T', bound=A)仅指定T必须是 的子类A。
T = TypeVar('T', A, B)仅指定T必须是子类A或子类B但不一定是两者。
我实际上想要类似的东西T = TypeVar('T', bound=[A, B]),这意味着T必须对A和进行子类化B。有这样做的标准方法吗?
以下示例的类型提示应该是什么:
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) python-typing ×10
python ×8
python-3.x ×6
mypy ×5
type-hinting ×2
annotations ×1
namedtuple ×1
nonetype ×1
oop ×1
plotly ×1
python-3.6 ×1
python-3.8 ×1
python-mro ×1
sqlalchemy ×1