跳转到主要内容

纯Python实现的近乎实时混合运行时-静态类型检查,速度极快。

项目描述

beartype Read The Docs (RTD) status beartype continuous integration (CI) status beartype test coverage status

Beartype文档位于ReadTheDocs(RTD)。它可读性高,结构清晰,对您的大脑深层褶皱有舒缓作用。打开您的思想,进入一个让你在工作中筋疲力尽的平凡知识海洋。进入... 熊百科:

https://beartype.readthedocs.io

您现在正在阅读的文档曾经是一个单块文件,大小约为316Kb,据称有22%的DevOps开发人员会因阅读它而感到头痛。为了您的安全,那个文档已经不再存在。这就是beartype对您的关怀。

Beartype是一个开源纯PythonPEP兼容近似实时混合运行时静态第三代类型检查器,强调效率、可用性、我们刚刚编造的不确定术语和令人兴奋的双关语。

# Install beartype.
$ pip3 install beartype
# Edit the "{your_package}.__init__" submodule with your favourite IDE.
$ vim {your_package}/__init__.py      # <-- so, i see that you too vim
from beartype.claw import beartype_this_package       # <-- hype comes
beartype_this_package()                               # <-- hype goes

Beartype现在隐式地检查您包中所有子模块中的所有注释类、可调用对象和变量赋值。恭喜,这一天所有的错误都将消失。

但为什么只在您的代码中停下来呢?您的应用程序依赖于大量其他包、模块和服务。那些代码中充满了多少传染病?您即将找到答案。

# ....................{ BIG BEAR                        }....................
# Warn about type hint violations in *OTHER* packages outside your control;
# only raise exceptions from violations in your package under your control.
# Again, at the very top of your "{your_package}.__init__" submodule:
from beartype import BeartypeConf                              # <-- this isn't your fault
from beartype.claw import beartype_all, beartype_this_package  # <-- you didn't sign up for this
beartype_this_package()                                        # <-- raise exceptions in your code
beartype_all(conf=BeartypeConf(violation_type=UserWarning))     # <-- emit warnings from other code

Beartype现在隐式地检查所有包中所有子模块的所有注释类、可调用对象和变量赋值。当您的包违反类型安全时,beartype会引发异常。当任何其他包违反类型安全时,beartype只会发出警告。您听到的胜利的喇叭声可能正是您的用户在欢呼。这就是质量保证是如何赢得的。

Beartype还发布了一系列API,用于对类型检查进行精细控制()。对于那些即将进行质量保证的人,beartype向您致敬。您想了解更多吗?

# 让我们开始吧。 $ python3

# ....................{ RAISE THE PAW                   }....................
# Manually enforce type hints across individual classes and callables.
# Do this only if you want a(nother) repetitive stress injury.

# Import the @beartype decorator.
>>> from beartype import beartype      # <-- eponymous import; it's eponymous

# Annotate @beartype-decorated classes and callables with type hints.
>>> @beartype                          # <-- you too will believe in magic
... def quote_wiggum(lines: list[str]) -> None:
...     print('“{}\n\t— Police Chief Wiggum'.format("\n ".join(lines)))

# Call those callables with valid parameters.
>>> quote_wiggum(["Okay, folks. Show's over!", " Nothing to see here. Show's…",])
Okay, folks. Show's over!
 Nothing to see here. Show's…”
    Police Chief Wiggum

# Call those callables with invalid parameters.
>>> quote_wiggum([b"Oh, my God! A horrible plane crash!", b"Hey, everybody! Get a load of this flaming wreckage!",])
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<string>", line 30, in quote_wiggum
  File "/home/springfield/beartype/lib/python3.9/site-packages/beartype/_decor/_code/_pep/_error/errormain.py", line 220, in get_beartype_violation
    raise exception_cls(
beartype.roar.BeartypeCallHintParamViolation: @beartyped
quote_wiggum() parameter lines=[b'Oh, my God! A horrible plane
crash!', b'Hey, everybody! Get a load of thi...'] violates type hint
list[str], as list item 0 value b'Oh, my God! A horrible plane crash!'
not str.

# ....................{ MAKE IT SO                      }....................
# Squash bugs by refining type hints with @beartype validators.
>>> from beartype.vale import Is  # <---- validator factory
>>> from typing import Annotated  # <---------------- if Python ≥ 3.9.0
# >>> from typing_extensions import Annotated   # <-- if Python < 3.9.0

# Validators are type hints constrained by lambda functions.
>>> ListOfStrings = Annotated[  # <----- type hint matching non-empty list of strings
...     list[str],  # <----------------- type hint matching possibly empty list of strings
...     Is[lambda lst: bool(lst)]  # <-- lambda matching non-empty object
... ]

# Annotate @beartype-decorated callables with validators.
>>> @beartype
... def quote_wiggum_safer(lines: ListOfStrings) -> None:
...     print('“{}\n\t— Police Chief Wiggum'.format("\n ".join(lines)))

# Call those callables with invalid parameters.
>>> quote_wiggum_safer([])
beartype.roar.BeartypeCallHintParamViolation: @beartyped
quote_wiggum_safer() parameter lines=[] violates type hint
typing.Annotated[list[str], Is[lambda lst: bool(lst)]], as value []
violates validator Is[lambda lst: bool(lst)].

# ....................{ AT ANY TIME                     }....................
# Type-check anything against any type hint – anywhere at anytime.
>>> from beartype.door import (
...     is_bearable,  # <-------- like "isinstance(...)"
...     die_if_unbearable,  # <-- like "assert isinstance(...)"
... )
>>> is_bearable(['The', 'goggles', 'do', 'nothing.'], list[str])
True
>>> die_if_unbearable([0xCAFEBEEF, 0x8BADF00D], ListOfStrings)
beartype.roar.BeartypeDoorHintViolation: Object [3405692655, 2343432205]
violates type hint typing.Annotated[list[str], Is[lambda lst: bool(lst)]],
as list index 0 item 3405692655 not instance of str.

# ....................{ GO TO PLAID                     }....................
# Type-check anything in around 1µs (one millionth of a second) – including
# this list of one million 2-tuples of NumPy arrays.
>>> from beartype.door import is_bearable
>>> from numpy import array, ndarray
>>> data = [(array(i), array(i)) for i in range(1000000)]
>>> %time is_bearable(data, list[tuple[ndarray, ndarray]])
    CPU times: user 31 µs, sys: 2 µs, total: 33 µs
    Wall time: 36.7 µs
True

Beartype将RustC++启发的零成本抽象引入到动态类型Python的无序世界,通过在函数和方法的粒度上强制执行类型安全,以对抗由Python社区标准化的类型提示,以O(1)非摊销最坏情况时间以及可忽略的常数因子。如果前面的句子是不可读的术语,请查看我们友好且易于理解的常见问题解答

Beartype以可移植的方式Python 3中实现,通过GitHub Actions × tox × pytest × Codecov进行持续的压力测试,并许可分发在MIT许可下。Beartype没有运行时依赖项,只有一个测试时依赖项,以及一个文档时依赖项。Beartype支持所有积极开发的Python版本、所有Python包管理器以及多个平台特定的包管理器。

项目详情


下载文件

下载适用于您平台的文件。如果您不确定选择哪个,请了解更多关于 安装包 的信息。

源分布

beartype-0.19.0.tar.gz (1.3 MB 查看哈希值)

上传时间

构建分布

beartype-0.19.0-py3-none-any.whl (1.0 MB 查看哈希值)

上传时间 Python 3

支持者

AWS AWS 云计算和安全赞助商 Datadog Datadog 监控 Fastly Fastly CDN Google Google 下载分析 Microsoft Microsoft PSF 赞助商 Pingdom Pingdom 监控 Sentry Sentry 错误记录 StatusPage StatusPage 状态页面