• Stars
    star
    2,441
  • Rank 18,144 (Top 0.4 %)
  • Language
    Python
  • License
    MIT License
  • Created about 4 years ago
  • Updated 16 days ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Unbearably fast near-real-time hybrid runtime-static type-checking in pure Python.

beartype β€”[ the bare-metal type checker ]β€”

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

⚠

Beartype documentation lives at ReadTheDocs (RTD). It's readable, structured, and soothing to the deep folds of your big galactic brain. Open your mind to an ocean of mundane knowledge that will exhaust you at work. Enter... the Bearpedia:

https://beartype.readthedocs.io

The document you are now reading was once a monolithic ~316Kb file known to induce migraines in 22% of the whole devops population. For your safety, that document no longer exists. This is how much beartype cares.

Beartype is an open-source PEP-compliant near-real-time pure-Python runtime type checker emphasizing efficiency, usability, and thrilling puns.

# Install beartype.
$ pip3 install beartype
# So let's do this.
$ python3
# Import the @beartype decorator.
>>> from beartype import beartype

# Annotate @beartype-decorated classes and callables with type hints.
>>> @beartype
... 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.

# ..................{ VALIDATORS  }..................
# Squash bugs by refining type hints with 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 brings Rust- and C++-inspired zero-cost abstractions into the lawless world of dynamically-typed Python by enforcing type safety at the granular level of functions and methods against type hints standardized by the Python community in O(1) non-amortized worst-case time with negligible constant factors. If the prior sentence was unreadable jargon, see our friendly and approachable FAQ for a human-readable synopsis.

Beartype is portably implemented in Python 3, continuously stress-tested via GitHub Actions Γ— tox Γ— pytest Γ— Codecov, and permissively distributed under the MIT license. Beartype has no runtime dependencies, only one test-time dependency, and only one documentation-time dependency. Beartype supports all actively developed Python versions, all Python package managers, and multiple platform-specific package managers.