Tip

Feed the bear! The bear is rifling around in the refuse pile outside. <GitHub Sponsors_> You feel sadness, then trepidation.

Beartype is an open-source pure-Python PEP-compliant near-real-time hybrid runtime-static third-generation type-checker emphasizing efficiency, usability, unsubstantiated jargon we just made up, and thrilling puns.

Beartype enforces type hints across your entire app in two lines of runtime code with no runtime overhead. If seeing is believing, prepare to do both those things.

    # 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

    # At the very top of your "{your_package}.__init__" submodule:
    from beartype.claw import beartype_this_package  # <-- boilerplate for victory
    beartype_this_package()                          # <-- yay! your team just won

Beartype now implicitly type-checks all annotated classes, callables, and variable assignments across all submodules of `{your_package}`. Congrats. This day all bugs die. …server slowly crashes

Beartype also publishes a plethora of APIs for fine-grained control over type-checking. For those who are about to QA, beartype salutes you. Would you like to know more?

    # So let's do this.
    $ 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 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.

# The Typing Tree

Welcome to the Bearpedia – your one-stop Encyclopedia Beartanica for all things @beartype. It’s “typing or bust!” as you…

Bear with Us

- Bearpedia
- Install
  - Platform
    - macOS
    - Arch Linux
    - Gentoo Linux
- tl;dr
- ELI5
  - Comparison
    - …versus Static Type-checkers
    - …versus Runtime Type-checkers
  - Quickstart
    - Standard Hints
      - Toy Example
      - Industrial Example
  - Tutorial
    - Builtin Types
    - Arbitrary Types
    - Unions of Types
    - Optional Types
  - Would You Like to Know More?
- API
  - The Left-Paw Path
- FAQ
  - What is beartype?
  - What is typeguard?
  - When should I use beartype?
  - Does beartype do any bad stuff?
  - Does beartype actually do anything?
  - How much does all this really cost?
  - Beartype just does random stuff? Really?
  - What does “pure-Python” mean?
  - What does “near-real-time” even mean? Are you just making stuff up?
  - What does “hybrid runtime-static” mean? Pretty sure you made that up, too.
  - “Third-generation type-checker” doesn’t mean anything, does it?
  - How do I type-check…
    - …Boto3 types?
    - …JAX arrays?
    - …NumPy arrays?
    - …PyTorch tensors?
    - …mock types?
    - …pandas data frames?
    - …the current class?
    - …under VSCode?
    - …under [insert-IDE-name-here]?
  - How do I *NOT* type-check something?
  - Why is @leycec’s poorly insulated cottage in the Canadian wilderness so cold?
- BigData™
- Code
  - Beartype Code Generation: It’s All for You
    - Identity Decoration
    - Unconditional Identity Decoration
    - Shallow Identity Decoration
    - Deep Identity Decoration
    - Constant Decoration
      - Constant Builtin Type Decoration
      - Constant Non-Builtin Type Decoration
      - Constant Shallow Sequence Decoration
      - Constant Deep Sequence Decoration
      - Constant Nested Deep Sequence Decoration
- Beartype Dev Handbook: It’s Handy
  - Dev Workflow
  - Moar Depth
  - Moar Compliance
- Math
  - Beartype Timings
    - Timings Overview
    - Timings Lower Bound
      - Formulaic Formulas: They’re Back in Fashion
      - Function Call Overhead: The New Glass Ceiling
      - Holy Balls of Flaming Dumpster Fires
      - But, But… That’s Not Good Enough!
  - Nobody Expects the Linearithmic Time
- Moar
  - Runtime Type Checkers
  - Runtime Data Validators
  - Static Type Checkers

Let’s type this.

# License

Beartype is open-source software released under the permissive MIT license.

# Funding

Beartype is financed as a purely volunteer open-source project via GitHub Sponsors, to whom our burgeoning community is eternally indebted. Without your generosity, runtime type-checking would be a shadow of its current hulking bulk. We genuflect before your selfless charity, everyone!

Prior official funding sources (yes, they once existed) include:

1. A Paul Allen Discovery Center award from the Paul G. Allen Frontiers Group under the administrative purview of the Paul Allen Discovery Center at Tufts University over the period 2015—2018 preceding the untimely death of Microsoft co-founder Paul Allen, during which beartype was maintained as the private `@type_check` decorator in the Bioelectric Tissue Simulation Engine (BETSE). Phew!

# Contributors

Beartype is the work product of volunteer enthusiasm, excess caffeine, and sleepless Wednesday evenings. The brave GitHubbers hurtled the pull request (PR) gauntlet so that you wouldn’t have to.

It’s a heavy weight they bear. Applaud them as they buckle under the load!