python >=3.5 : Checking type annotation at runtime

标签 python python-3.x type-hinting mypy python-typing

typing模块(或任何其他模块)展示一个 API 以在运行时对变量进行类型检查,类似于 isinstance()但了解 typing 中定义的类型类?

我想做一些类似于:

from typing import List
assert isinstance([1, 'bob'], List[int]), 'Wrong type'

最佳答案

我正在寻找类似的东西并找到了图书馆 typeguard .这可以在任何你想要的地方自动进行运行时类型检查。还支持直接检查问题中的类型。从文档中,

from typeguard import check_type

# Raises TypeError if there's a problem
check_type('variablename', [1234], List[int])

关于 python >=3.5 : Checking type annotation at runtime,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43646823/

相关文章:

定义结构时python cffi解析错误

具有非整数索引的 Python Numpy 二维数组

python - 用于打印 pandas 数据框的 GUI

python - 如何用 python-attrs 构造解决 "unexpected keyword argument",让 mypy 开心?

python - 类型提示适合函数参数而不是返回类型

python - 在python中解析CSV的特定列

python - 跨多个进程python 2.x的线程安全打印

python - 我的函数没有运行,但是当我在函数之外运行代码时它可以工作

python - 我如何在没有Restful Api的情况下使用Elasticsearch

python - 为什么 Python 不抛出 '-> type' 函数定义的类型异常?