- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我正在尝试注释以下代码。
当同时定义了 zone
和 zones
时,或者当定义了 file
时(但不是同时定义了两者),该函数将起作用:
def get_file(zone: str, zones: dict[str, str]) -> pathlib.Path:
pass
def connect(
zone: str | None = None,
zones: dict[str, str] | None = None,
file: pathlib.Path | None = None,
) -> bool:
file = file or get_file(zone, zones)
但这让 mypy
生气了 -
1. Argument of type "str | None" cannot be assigned to parameter "zone" of type "str" in function "_get_vpn_file"
Type "str | None" cannot be assigned to type "str"
Type "None" cannot be assigned to type "str"
2. Argument of type "dict[str, str] | None" cannot be assigned to parameter "zones" of type "dict[str, str]" in function "_get_vpn_file"
Type "dict[str, str] | None" cannot be assigned to type "dict[str, str]"
Type "None" cannot be assigned to type "dict[str, str]"
然后我尝试进行一些激进的类型缩小:
def _check_params_are_ok(
zone: str | None, zones: dict[str, str] | None, file: pathlib.Path | None,
) -> tuple[str, dict[str, str], None] | tuple[None, None, pathlib.Path]:
if zone is not None and file is not None:
raise ValueError("Pass `file` or `zone`, but not both.")
if zone is not None and zones is None:
raise ValueError("connect: Must define `zones` when `zone` is defined.")
if zone is None and file is None:
raise ValueError("connect: Must define `zone` or `file`.")
assert file is not None or (zone is not None and zones is not None)
# Type narrowing
if zone is not None and zones is not None and file is None:
return zone, zones, file
if zone is None and zones is None and file is not None:
return zone, zones, file
raise NotImplementedError("This error from _check_params_ok shouldn't happen.")
def connect(
zone: str | None = None,
zones: dict[str, str] | None = None,
file: pathlib.Path | None = None,
) -> bool:
zone, zones, file = _check_params_are_ok(zone, zones, file)
file = file or get_file(zone, zones)
而且 mypy 仍然显示相同的错误。
即使添加非常明确的断言,Mypy 仍然显示相同的错误:
zone, zones, file = _check_params_are_ok(zone, zones, file)
if file is None:
assert zone is not None and zones is not None
file = file or get_file(zone, zones)
目前我找到的最佳解决方案是内联转换类型,但这会影响代码的可读性并使行难以阅读:
file = file or get_file(cast(str, zone), cast(dict[str, str], zones))
有没有什么好的方法可以缩小类型?
最佳答案
在您的代码中,当您执行 - 正如您所说的那样 - 非常清晰的断言时,您只能在 if< 的主体中分配给
声明:file
/
if file is None:
assert zone is not None and zones is not None
file = get_file(zone, zones)
# file is now a pathlib.Path object
assert file.is_file() # this is now valid
那么你会非常明确,mypy
不应该再对此提示了。
关于mypy - 短路 `or` 的窄类型,当我有两种可能的情况时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74301962/
我正在探索 Python 的静态类型检查器,并在设置 Visual Studio Code 时遇到了不同的包。我已经安装了 python-language-server 用于 linting 和格式化
我使用 disallow-untyped-defs 选项运行 mypy。当我用@overload 注释函数类型并在定义中省略注释时,mypy 仍然会产生错误。对我来说,似乎应该将函数视为带注释的。 例
我想将以下内容添加到 pre-commit对于一个团队: - repo: https://github.com/pre-commit/mirrors-mypy rev: 'v0.720'
我正在尝试将 MyPy 与使用 ruamel.yaml 的模块一起使用,而 Mypy 无法找到 ruamel.yaml,即使 Python 可以毫无问题地找到它。我很困惑,因为我也找不到名为 YAML
可以通过 json.dumps 转换为 JSON 字符串的值是: - 标量:数字和字符串 - 容器:映射和可迭代 Union[str, int, float, Mapping, Iterable] 你
我想将 TypedDict 与 Union 结合起来。这样函数就可以返回 A 或 B。 Mypy 能够直接正确检测 TypedDict 返回类型。但是当 TypedDict 嵌套在 Union 中时,
我正在接收来自远程方的消息,这些消息被解码为如下所示的类: class SomeMessage(MessageType): foo: Optional[int] bar: Option
我试图找到一种方法来区分参数是否已传递给方法。例如,我有以下功能: @dataclass class Record: id: int name: str completed_a
我无法让 Mypy 在这里识别正确的类型。我想要做的就是为类创建一个 dict 名称,这样我就可以通过提供作为其属性的 type_name 来获取该类。也许是因为 dataclass 和 datacl
我有一个变量 x 和一个文字列表(比如 0、1、2)。我想将 x 转换为这些文字之一:如果 x 在列表中,我返回它;否则我返回一个后备值: from typing import Literal, Se
考虑以下代码: def foo(a: dict[str | tuple[str, str], str]) -> None: pass def bar(b: dict[str, str]) ->
我有以下代码片段: from typing import TypedDict class Super(TypedDict): foo: int class SubA(Super): b
我正在尝试理解 typing.overload 并将其应用到一个简单的案例中,我想要一个接受输入的函数 x: Literal["foo", "bar"] 并返回列表 [x]。 我希望 mypy 根据x
我正在使用 Python 3.8.1 和 mypy 0.782。我不明白为什么 mypy 提示以下代码: from typing import Union, List, Dict Mytype = U
我正在尝试定义方法 foo 的返回值作为 AbstractChild 的列表子类实例,但 mypy 一直给我一个错误。 class AbstractParent(ABC): @abstract
class BaseClass: p: int class DerivedClass(BaseClass): q: int def p(q: Callable[[BaseClass],
有没有办法让这项工作 from typing import Literal def foo(bar: Literal["bar"]) -> Literal["foo"]: foo = "foo
一些功能如 numpy.intersect1d返回不同的类型(在这种情况下是一个 ndarray 或三个 ndarray 的元组)但编译器只能推断其中一个,所以如果我喜欢: intersection:
可以通过获取可能成员的列表来创建枚举,我正在这样做: # example_issue.py import enum yummy_foods = ["ham", "cheese"] foods = en
我有一组要在 python3.6 环境中运行的命名空间包。 它们分别设置如下: if sys.version_info < (3, 6): print("Python versions < 3
我是一名优秀的程序员,十分优秀!