我开始在 Python 中使用类型提示。我有以下功能:
def func(arg: Optional[str]):
# ...
# make sure arg is a string and not None
do_something(arg) # do_something expects a string
Run Code Online (Sandbox Code Playgroud)
仅当 arg 确实是一个字符串而不是 None 时,才能到达对 的调用do_something,但 mypy 无法自行解决(这不是 mypy 问题,它无法理解所有内容)。所以 mypy 标记了调用,do_something因为 arg 可能是 None
在 Typescript 中,可以使用感叹号来处理类似的情况arg!- 感叹号告诉静态分析器arg不是未定义的。Python中有类似的东西吗?
Tensorflow是一个超级重磅的导入。我只想在需要时导入它。但是,我有一个像这样的模型加载函数:
from typing import Dict, Any
from keras.models import Model # Heavy import! Takes 2 seconds or so!
# Model loading is a heavy task. Only do it once and keep it in memory
model = None # type: Optional[Model]
def load_model(config: Dict[str, Any], shape) -> Model:
"""Load a model."""
if globals()['model'] is None:
globals()['model'] = create_model(wili.n_classes, shape)
print(globals()['model'].summary())
return globals()['model']
Run Code Online (Sandbox Code Playgroud) 当尝试从作为实例属性的类继承时,就会出现问题。这个 mcve 重现了它,我将把下面问题的其余部分留给后代:
class A:
class SubA:
pass
a = A()
class B(a.SubA):
pass
Run Code Online (Sandbox Code Playgroud)
mypy输出:
Name 'a.SubA' is not defined
Run Code Online (Sandbox Code Playgroud)
这通过:
Name 'a.SubA' is not defined
Run Code Online (Sandbox Code Playgroud)
本相关问题中的示例几乎正是在命名空间Flask-SQLAlchemy下提供声明性基类的内容db。在该问题中,mypy维护者声称他们不会支持该模式。
我的问题是,上述模式有什么不正确以至于mypy不支持它?特别是在大型项目(例如Flask-SQLAlchemy.
此外,用户Flask-SQLAlchemy和mypy在项目中管理此内容的最佳方式是什么?
这个问题与缺少存根无关Flask-SQLAlchemy。接受这一点后,我遇到了这个问题。
请帮助我理解为什么以下内容不能按我的预期工作。
在我的环境中我只安装Flask-SQLAlchemy了mypy。
我已经mypy配置了ignore_missing_imports = True.
跳过mypy以下内容:
class A:
class SubA:
pass
class B(A.SubA):
pass
Run Code Online (Sandbox Code Playgroud)
揭示了:
error: Name 'db.Model' is not …Run Code Online (Sandbox Code Playgroud) 我试图理解Getter[T]以下代码中的类型提示:
T = TypeVar('T')
Getter = Callable[[T, str], str]
class AbstractClass(abc.ABC):
@abc.abstractmethod
def extract(
self,
get_from_carrier: Getter[T], # <---- See here
...
) -> Context:
Run Code Online (Sandbox Code Playgroud)
非常感谢您的帮助,因为我一直为此而伤透脑筋。
原始源代码来自OpenTelemetry 项目文件“textmap.py”:
import abc
import typing
from opentelemetry.context.context import Context
TextMapPropagatorT = typing.TypeVar("TextMapPropagatorT")
Setter = typing.Callable[[TextMapPropagatorT, str, str], None]
Getter = typing.Callable[[TextMapPropagatorT, str], typing.List[str]]
class TextMapPropagator(abc.ABC):
"""This class provides an interface that enables extracting and injecting
context into headers of HTTP requests.
...
"""
@abc.abstractmethod
def extract(
self, …Run Code Online (Sandbox Code Playgroud) from typing import List
class Base(object):
pass
class A(Base):
pass
class B(Base):
pass
a: List[A] = []
b: List[B] = []
c: List[Base] = a + b
Run Code Online (Sandbox Code Playgroud)
我正在Expected type 'List[A]' (matched generic type 'List[_T]'), got 'List[B]' instead继续b。
我如何获得正确的警告,因为显然类型很好。
我在 PyCharm 项目中有以下 Python 代码:
class Category:
text: str
a = Category()
a.text = 1.5454654 # where is the warning?
Run Code Online (Sandbox Code Playgroud)
当我尝试设置错误类型的属性时,编辑器应该显示警告。看看下面的设置:
我想类型提示一个方法,该方法可能会接收对 A 或 A 的子类进行操作的 Callable:
def do(f: Callable[[A], None])
Run Code Online (Sandbox Code Playgroud)
我也尝试过:
def do(f: Callable[[typing.Type[A]], None])
Run Code Online (Sandbox Code Playgroud)
完整的虚拟示例如下所示:
class A:
n = 1
class B(A):
n = 2
def something_a(x: A):
print(x.n)
def something_b(x: B):
print(x.n)
def do(f: Callable[[A], None]):
f(B())
do(something_a) # ok
do(something_b) # PyCharm type check warnning
Run Code Online (Sandbox Code Playgroud) 两个python方法定义为:
def function() -> Optional[ast.Module]:
pass
def something(t: ast.Module) -> None:
pass
Run Code Online (Sandbox Code Playgroud)
在呼叫者中:
var = function()
if var:
do_something(var)
Run Code Online (Sandbox Code Playgroud)
类型检查器抱怨我无法将Optional[t]传递给t。我想象有某种铸造机制,但我没有想到。
准确地说,这是一个单元测试,如下所示:
self.assertIsNotNone(var)
do_something(var)
Run Code Online (Sandbox Code Playgroud)
关于可能重复的可选类型注释。检查是否为“无”后使用值?,
new_var: ast.Module = var
Run Code Online (Sandbox Code Playgroud)
得到相同类型的错误。
是否需要“如果”?
我有一本像这样的字典:
d = { 'my_label': ClassInstance() }
Run Code Online (Sandbox Code Playgroud)
我想指定类型提示来指示键是字符串,值是ClassInstance.
这在 Python 3.8 中可能吗?
我发现TypedDict但这似乎试图指示一组固定的键。我允许任何字符串作为键。
我使用 vscode,发现 Python linter 无法检测何时使用与其签名定义不同类型的参数调用 python 函数。
在这种情况下,该函数需要 atyping.Type[Exception]而不是Exception:
Pycharm检测到这种情况:
我认为mypy不会检测到这个,因为它使用该typing模块(mypy检测内置类型中的类型不匹配)。
注意:我遵循了这篇 SO帖子( )中的标志建议,--check-untyped-defs但它不起作用。
python-typing ×10
python ×9
mypy ×3
python-3.x ×2
typechecking ×2
dictionary ×1
generics ×1
lint ×1
pycharm ×1
tensorflow ×1
type-hinting ×1
typescript ×1