NewYour coding agent can read the release notes before it upgrades.Set up the MCP server →
PyPI, #324 most downloaded on PyPI
Unbearably fast near-real-time pure-Python runtime-static type-checker.
Latest stable
0.23.1
Last release 1 months ago
11 Oct 2026
Ships unpredictably
gaps range from 8 days to 8 months
Nearly every release is documented
notes for 52 of 56 stable releases
3 versions withdrawn
withdrawn after publishing
6 years old
69 releases · first in 2020
Drag across the ruler to compare, or tap a release to open it.
@beartype 0.22.3 descends softly. A crinkled QA leaf drifts somnabulently. Autumn gusts on GitHub. Rain hails on PyPI. These are the haiku of our Pyth
@beartype 0.22.3 descends softly. A crinkled QA leaf drifts somnabulently. Autumn gusts on GitHub. Rain hails on PyPI. These are the haiku of our Pythonic lives:
# Via "pip", the once-great venerable master packager now fallen on hard times:
$ pip install --upgrade beartype # <-- you go, old man pip
# Via "uv", the plucky upstart spiky-haired kid wielding a sword larger than its body:
$ uv lock --upgrade-package # <-- you are cleared for takeoff
That's right. uv installation instructions. It's happening, people.
<sup>@beartype 0.22.3 dances the happy dance as your codebase watches in horror</sup>
@beartype 0.22.3 is helping @leycec and his beautiful science wife to eat food. Thanks entirely to...
This release comes courtesy these proud GitHub Sponsors, without whom everyone in the @leycec family would currently be eating grasshoppers in the abandoned back lot again:
If you represent a security-conscious corporate, government, or non-profit, the best way bar none for you to support @beartype and secure your own workflow is by subscribing to Tidelift through SonarQube Advanced Security. Security giant Sonar recently acquired Tidelift, guaranteeing the economic viability of the Tidelift model for billions of future open-source projects that have yet to be born. Join the jargon-laden conversation and pay someone else to think about unreadable acronyms like SAST, SCA, and SBOM for once.
Thanks so much, masters of fintech and lifted tides.
<sup>The Masters of Fintech and Lifted Tides. That's who.</sup>
@beartype 0.22.3 is a patch release with a big heart, but not a lot to say. It means well, but it doesn't do much. But what it does do, it does so well:
redis-py Python client! @beartype now officially supports Redis in general and the redis.Redis class specifically. Hype it! :godmode:0.22.3 drops Python 3.9 support a week ahead of its official End-of-Life (EoL). I generally prefer to abandon Python compatibility with minor releases (e.g., 0.23.0) rather than patch releases like this. But... I gotta make an exception for Bad Boy Python 3.9. I'm sorry, everyone. It got axed. :goberserk:
<sup>@beartype 0.22.3: it's funny until Helmet Bear eats your code</sup>
...to financially feed @leycec and his friendly @beartype through either:
Cue hypnagogic rave music that encourages fiscal irresponsibility. :musical_note: :musical_keyboard: :notes:
@beartype high-fives the reclusive secret society of worldwide bear bros who might possibly care about this. You are the select few. The elect enlightened. You are:
<sup>@beartype 0.22.3 at 2:01AM in the morning</sup>
Your coding agent can read these notes before it upgrades. Set up the MCP server →
@beartype users who discover security vulnerabilities are invited to privately disclose those vulnerabilities by submitting a GitHub-managed security…
@beartype is proud as a cub gnawing its first salmon to announce: @beartype has been Tidelifted! For our security-conscious corporate and government userbase, the best way to secure your enterprise and support @beartype is now through Tidelift vis-a-vis a SonarQube Advanced Security subscription. More on that later. We now return to your regularly scheduled release party. DJ Leycec in residence. Hit those fat QA jams.
Beartype 0.22.0 0.22.1 0.22.2 portals into the mortal plenum with a disturbing "WHOOOMP!" As you panic, all the oxygen in the room is rapidly vacuumed into an adjacent hyperdimension. It's not @beartype's safest entrance – but it's one we're all sure to remember. This is @beartype 0.22.2: <sup>don't ask what happened to 0.22.0. just... don't.</sup>
pip install --upgrade --pre beartype # beartype casts magic missile on the darkness
The central dogma of @beartype 0.22.2 is LLM compatibility. Do you like LLM? Do you like compatibility? Then your code likes @beartype 0.22.2 (even against your better judgement). But before the liking starts...
<sup>@beartype 0.22.2 salutes you who are about to code</sup>
@leycec and his beautiful science wife are eating well. Thanks entirely to...
This release comes courtesy these proud GitHub Sponsors, without whom @leycec's cats would currently be eating grasshoppers in the abandoned back lot again:
Additional financial shout-outs to @ilyapoz (@Ilia Pozhilov), the amazing former Yandex code cosmonaut who graciously donated a pile of Georgian lari to @beartype this go-around. Apparently, the lari is denominated in the ლ Unicode character. What a symbol! It looks like a beautiful hat. If only the Canadian dollar was half as manly. :sob:
Thanks so much, masters of fintech and Yandex.
<sup>The Masters of Fintech and Yandex. That's who.</sup>
This release also comes courtesy Tidelift, which very graciously pays out recurring income to security-sensitive open-source projects like @beartype, NumPy, and other stuff you probably care about. @beartype joining Tidelift has super-positive implications for Python's broader QA community – including:
If you represent a security-conscious corporate, government, or non-profit, the best way bar none for you to support @beartype and secure your own workflow is by subscribing to Tidelift through SonarQube Advanced Security. Security giant Sonar recently acquired Tidelift, guaranteeing the economic viability of the Tidelift model for billions of future open-source projects that have yet to be born. Join the jargon-laden conversation and pay someone else to think about unreadable acronyms like SAST, SCA, and SBOM for once.
<sup>Pictured: Artistic rendition of the @beartype development process before Tidelift. You weren't supposed to see this.</sup>
You really want to bump the @beartype requirement in your pyproject.toml file. Preserve end user sanity tomorrow by explicitly requiring a minimum of @beartype >=0.22.2 today: e.g.,
# In your top-level "pyproject.toml" configuration:
dependencies = [
...
"beartype >=0.22.2", # <-- once you go 0.22.2, you go 0.22.2 for life
...
]
Why? Bear with us. This explanation may bore you. Imagine what typing this out felt like.
Prior versions of @beartype are fundamentally incompatible with Python 3.14. Python packagers like pip and uv do not update packages by default. Unless you bump your @beartype requirement, your existing userbase who already installed your package will be unable to use your package under Python 3.14 – even after manually updating your package, because manually updating your package fails to transitively update all dependencies of your package by default. In other words, Python packaging still kinda sucks.
This is why...
<sup>@beartype looks stoically into the wind as everything breaks</sup>
beartype.claw import hooks have been supremely revamped. They still work the same, but they're now explicitly compatible with a lot more than they used to be. If you tried enabling beartype_this_package() but switched back to manually decorating everything with @beartype because beartype_this_package() spewed too many errors everywhere, please give beartype_this_package() a second chance:
# In the "{your_package}.__init__" submodule:
from beartype.claw import beartype_this_package
beartype_this_package() # <-- we're willing to swear on our pinkies that this works now
Let us know how it goes. If stuff is still busted, we'll immediately fix that stuff. We now have the necessary machinery in our abstract syntax tree (AST) transformer to support all (or most, anyway) compatibility woes previously associated with beartype.claw import hooks.
<sup>the new beartype.claw shamelessly dances for anyone</sup>
@beartype 0.22.2 dramatically improves compatibility across the board with the APIs, packages, and paradigms you care about. Because you care, we care. In fact, we spent whole months caring. We cared so much we're all cared out. The summer went away in a blitz of caring and we didn't even notice. Oh, Gods. The warmth has fled. The snow is coming. And all we have to show for it is massive compatibility gains across the board.
This includes:
<sup>@beartype 0.22.2 weeps from pride and accomplishment, but mostly sleep deprivation</sup>
Python 3.14. You care about Python 3.14 even if you don't know you care. @beartype now fully supports PEP 649 and 749 – landmark QA standards introduced by Python 3.14 that finally obsolete PEP 563. All these numbers mean something. We swear. Since all horror stories start with two nondescript teens in a Buick, let's start there:
from __future__ import annotations
That's PEP 563. And... that's now deprecated. PEP 749 officially deprecated PEP 563 a few months ago:
Sometime after the last release that did not support PEP 649 semantics (expected to be 3.13) reaches its end-of-life,
from __future__ import annotationsis deprecated. Compiling any code that uses the future import will emit a DeprecationWarning. This will happen no sooner than the first release after Python 3.13 reaches its end-of-life, but the community may decide to wait longer. After at least two releases, the future import is removed, and annotations are always evaluated as per PEP 649. Code that continues to use the future import will raise aSyntaxError, similar to any other undefined future import.
tl;dr: On October ~15th 2029, from __future__ import annotations will be officially deprecated. On October ~15th 2031, from __future__ import annotations will be removed entirely from the Python language. At that time, any module using from __future__ import annotations will raise a SyntaxError at importation time and thus become unimportable. In 2025, nobody should enable from __future__ import annotations voluntarily.
Sometime over the next several five years, you and your righteous dev team will require Python ≥ 3.14 as a mandatory dependency. That's just the way of the Python world. Planned obsolesce is the road we walk. When that happens, you'll no longer need from __future__ import annotations to declare forward references to undefined types in type hints like this:
# Look, Ma! No "from __future__ import annotations".
# We don't need the future where we're going.
from beartype import beartype
# Under Python ≥ 3.14, this just works. You annotated a function as accepting
# an instance of a type you haven't even declared yet. Yet, this is now fine.
# @beartype accepts you and your suspicious code for you who are.
@beartype
def useless_func(forward_reference_to_undefined_type: ThisJustWorksNow) -> ThisJustWorksNow:
return forward_reference_to_undefined_type
# Of course, you *DO* have to eventually define the undefined type used above.
# If you don't, everything will still blow up. It's not @beartype's fault.
# Python 3.14 made us do it... We blame Guido.
class ThisJustWorksNow(object):
pass
Unquoted forward references are thus baked into Python 3.14. Order of type hints and types is no longer significant. Define and annotate stuff in any order you like.
@beartype 0.22.2: because life is too short and code is too long.
<sup>@beartype: always ready to rip its shirt off at the slightest provocation</sup>
@beartype 0.22.2 now ships with out-of-the-box support for Bad Boy LLM APIs that defy community standards, mental health, and your last hair follicles. This includes:
These APIs are awesome, because they changed the world. But they're also hostile to literally every other Python decorator in existence. @beartype is a Python decorator in existence. Thus, these APIs are hostile to @beartype.
Why? Because they all define decorator-hostile decorators: that is, decorators that prevent other decorators from being applied. That's not how decorators are supposed to work. You're supposed to be able to apply decorators in any arbitrary order. That was the deal, LLM APIs! Apparently, LLM APIs hated that deal. Their decorators destructively transform your normal functions and methods (which are decoratable by @beartype) into abnormal instances of API-specific types (which are not decoratable by @beartype).
In the worst case of both LangChain and FastMCP, these abnormal instances of API-specific types aren't even callable! They don't just destroy the types of what they decorate. They destroy the callability of what they decorate. What kind of compatibility-hostile API turns a function or method into an uncallable object that you can't do anything with anymore? LangChain and FastMCP. That's who.
Examples include:
@langchain_core.runnables.chain decorator function.@fastmcp.FastMCP.tool decorator method.@celery.Celery.task decorator method.@beartype 0.22.2 now officially supports decorator-hostile decorators like this. It cost us our summer, but no price is too high. Okay. The price was pretty high. But this is the AI-ML-LLM hype train we're talking about. You either board that train or you prepare to eat everybody else's dust as they point fingers and cruelly guffaw into their monocles at you. @beartype prefers to board that train.
@beartype walks its own road, though. @beartype boards that train in its own special way. Specifically, @beartype now maintains two internal databases efficiently structured as trie prefix search trees:
beartype.claw import hooks then:
@beartype decorator before (rather than after) the last decorator-hostile decorator in existing chains of two or more consecutive decorators decorating your callables and types in your modules.@beartype decorator now silently ignores attempts to decorate instances of these problematic types. Don't even bother! They're busted, @beartype. At least we no longer are. :sweat_smile:It's... complicated. Really, really complicated. There's a doctoral PhD thesis somewhere here for somebody who wants one. Me? I just wanna sleep. Blessed sleep! Take me now!
<sup>left: @beartype. right: langchain, fastmcp, and celery. you think we forgive you that easily!?</sup>
Polars is the vibrant Pandas alternative everyone loves. 35k GitHub stars cannot be wrong. Although I feel jealousy when I hear numbers like that, @beartype now officially supports validation of Polars DataFrames vis-a-vis Pandera – the only sane way to validate the integrity of your fragile DataFrames that are probably falling over as we speak. Poor guys.
Previously, @beartype only supported validation of Pandas DataFrames via Pandera. Now, @beartype supports both Pandas and Polars. This can only mean one thing. Our powers are growing at an exponential rate. The QA Singularity is upon us. Check out this terrifying exhibition of runtime validation run amok:
import pandera.polars as papol
import beartype
import pandera.typing.polars as pt
import polars as pl
class Schema(papol.DataFrameModel):
state: str
city: str
price: int = papol.Field(in_range={"min_value": 5, "max_value": 20})
@papol.check_types
@beartype.beartype
def test_schema(df: pl.DataFrame) -> pt.DataFrame[Schema]:
return df
df = pl.DataFrame({
"state": ["Ohio", "Ohio", "Ohio", "Nevada", "Nevada"],
"city": ["Youngstown", "Akron", "Columbus", "Reno", "Las Vegas"],
"price": [10, 20, 15, 14, 4]
# ^-- *VIOLATION*. so bad. so very bad. we're panicking. game over, man!
})
test_schema(df)
...which helpfully blows up with a human-readable exception that relieves you:
Traceback (most recent call last):
File "/home/leycec/tmp/mopy.py", line 24, in <module>
test_schema(df)
~~~~~~~~~~~^^^^
File "/home/leycec/py/pyenv/versions/3.13.2/lib/python3.13/site-packages/pandera/decorators.py", line 841, in _wrapper
return _check_arg("return", out)
File "/home/leycec/py/pyenv/versions/3.13.2/lib/python3.13/site-packages/pandera/decorators.py", line 722, in _check_arg
raise error_handler.schema_errors[0]
pandera.errors.SchemaError: error in check_types decorator of function 'test_schema':
Column 'price' failed validator number 0: <Check in_range: in_range(5, 20)> failure case
examples: [{'price': 4}]
@beartype: Bleeding-edge APIs named after magnetic dipoles? Yeah. We do that, too.
<sup>@beartype 0.22.2 pours one out for the DataFrame that didn't make it.</sup>
@beartype 0.22.2 fully supports PEP 646 – Variadic Generics. <sup>...for certain glib definitions of "fully supports."</sup>
PEP 646 is outrageously huge. It's the longest and cruelest typing standard published to date. Synopsizing that standard is a fool's errand. Thus, we now synopsize that standard. PEP 646 brings two things to the QA table. Let's go! :hurtrealbad:
<sup>I-I-Is that @beartype's arm she's holding up!? :open_mouth: </sup>
PEP 646 introduces type variable tuples (i.e., typing.TypeVarTuple(...) objects). Whereas good ol' PEP 484-compliant type variables (i.e., typing.TypeVar(...) objects) match only a single type (like MuhGeneric[int] for class MuhGeneric[T](): ...), type variable tuples greedily match zero or more types (like WoahGeneric[int, str, bool] for class WoahGeneric[*Ts](): ...).
The use case is tensors, supposedly. I personally press "F" to doubt that any real-world tensor frameworks will actually leverage type variable tuples. Doing so would inhibit forward compatibility with future tensor APIs in those frameworks. Why? Because type variable tuples match types greedily. Once you've exposed a type variable tuple to your end users through a public-facing generic type, you can never add any other type variables to that generic type without breaking backward compatibility. You're now permanently locked in to that generic type API for the rest of all time.
Aren't ordinary type variables like that too, though? No. You can always add additional type variables to normal generic types without breaking backward compatibility. How? PEP 696-compliant type variable defaults (e.g., T = TypeVar("T", default=int)). Press "F" if anyone would like me to babble incoherently more about all this.
That said, type variable tuples probably do have practical internal use. I'd never expose them to end users for the aforementioned reasons. They cause compatibility woes. Still, @beartype 0.22.2 now fully supports them. Use them! Reassure us that we didn't waste the entire summer on this! Oh, Gods... the summer... it's... it's gone, everybody. :weary:
<sup>@beartype 0.22.2 when it realized where the summer went</sup>
PEP 646 also introduces tuple type hint unpacking (e.g., tuple[int, *tuple[str, ...]]). This spec goes really hard really fast. The syntax is also kinda nasty. But the core idea is that you can now deeply type-check the contents of non-trivial tuple data structures. You may now be thinking:
"Uhh... wat? Tuple data structures? Can you even use tuples like data structures? Even if you can, should you? Wouldn't a tuple data structure promote unreadable and obfuscated code that not even the unpaid intern wants to maintain?"
Indeed! It's all true! You can use tuples like data structures. @beartype internally does this all the time. Why? Unjustifiable microoptimizations. Because CPython is highly internally optimized for tuple instantiation, access, and garbage-collection, tuples make the ideal read-only data structures for many perfidious purposes. CPython cares a lot about tuples. Tuples are the backbone of CPython's calling convention, because functions and methods returning multiple values implicitly return tuples of those values. This makes tuples the ideal data structures for implementing many pure-Python algorithms – especially recursive algorithms implemented iteratively.
Of course, tuple data structures do promote unreadable and obfuscated code that not even the unpaid intern wants to maintain. But that's not a problem if you're a dodgy codebase like @beartype. Ain't nobody maintaining this code except @leycec – a well-known glutton for punishment-by-dev-hell.
If you are like @leycec, you too can now type-check your shamefully growing heap of tuple data structures from Hell. How? PEP 646, yo. Previously, PEP 484 only let you type-check two simplistic kinds of tuple hints:
tuple[str, int], for example, is the fixed tuple hint matching tuples containing one string item followed by an integer item.tuple[str, ...], for example, is the variadic tuple hint matching tuples containing zero or more string items.That's great if your tuple data structures are simplistic. But they're probably not, are they? That's why you're still reading this at 4:17AM. Your wife is calling out for you in her fitful sleep, but you don't even care! This is riveting Internet reading right here!
So what if your tuple data structures are as complicated as your marriage? You reach for PEP 646 and @beartype 0.22.2. You can now unpack at most one child tuple hint inside another parent tuple hint. For reasons that will become clear shortly, most child tuple hints unpacked in this way are variadic. Do that and you've now defined a mixed fixed-variadic tuple hint that matches tuples containing (in order):
tuple[str, bytes, *tuple[int, ...], bool, float], for example, is the mixed fixed-variadic tuple hint matching tuples containing (in order) a string item, a byte string item, zero or more integer items, a boolean item, and a floating-point number item. Cool, right? But the coolness doesn't stop there. Consider cardinality. Old-school variadic tuple hints (like tuple[str, ...]) only match tuples containing zero or more items. But what if you want to match a positive number of items? Tuple hint unpacking trivially lets you do that, too.
tuple[str, *tuple[str, ...]], for example, is the mixed fixed-variadic tuple hint matching tuples containing one or more strings. This example then generalizes to arbitrary cardinality bound only by your patience and openness to syntactic barbarism. Want to match tuples containing a larger number of strings? Just keep prepending str child type hints until you're satisfied, exhausted, and dripping with sweat at 4:17AM.
tuple[str, str, str, str, str, *tuple[str, ...]], for example, is the mixed fixed-variadic tuple hint matching tuples containing five or more strings. It's silly. Yet, it works. Kinda.
@beartype 0.22.2: it's only silly if you admit it's silly.
<sup>beartype 0.22.2 proudly unpacks tuple hints as the wind blows its hair around</sup>
...to financially feed @leycec and his friendly @beartype through either:
Cue hypnagogic rave music that encourages fiscal irresponsibility. :musical_note: :musical_keyboard: :notes:
@beartype high-fives the reclusive secret society of worldwide bear bros who might possibly care about this. You are the select few. The elect enlightened. You are:
@posita, @wesselb, @tusharsadhwani, @JWCS, @patrick-kidger, @EtaoinWu, @iamrecursion, @Moosems, @langfield, @sylvorg, @Glinte, @cclauss, @sean-roelofs-ai, @kultura-luke, @jonathanberthias, @gotmax23, @adamtheturtle, @ilyapoz, @MilesCranmer, @rg936672, @ddorian, @k4ml, @riesentoaster, @LeonHilf, @jeertmans, @mzealey, @thetianshuhuang, @RomainBrault, @alisaifee, @ArneBachmannDLR, @JelleZijlstra, @tactile-metrology, @RobPasMue, @GithubCamouflaged, @kloczek, @uriyasama, @danielgafni, @JWCS, @rbroderi, @AlanCoding, @tvdboom, @crypdick, @jvesely, @komodovaran, @kaparoo, @MaximilienLC, @fleimgruber, @alexoshin, @gabrieldemarmiesse, @James4Ever0, @NLPShenanigans, @rtbs-dev, @yurivict, @st--, @murphyk, @dosisod, @Rogdham, @alisaifee, @denisrosset, @damarro3, @ruancomelli, @jondequinor, @harshita-gupta, @jakebailey, @denballakh, @jaanli, @creatorrr, @msvensson222, @avolchek, @femtomc, @AdrienPensart, @jakelongo, @Artur-Galstyan, @ArneBachmann, @danielward27, @WeepingClown13, @rbnhd, @radomirgr, @rwiegan, @brettc, @spagdoon0411, @helderco, @paulwouters, @jamesbraza, @dcharatan, @kasium, @AdrienPensart, @sunildkumar, @peske, @mentalisttraceur, @awf, @PhilipVinc, @dcharatan, @empyrealapp, @rlkelly, @KyleKing, @skeggse, @RomainBrault, @deepyaman, @minmax, @jedie, @pablovela5620, @thiswillbeyourgithub, @Logan-Pageler, @knyazer, @ilyapoz, @yuzhichang, @Fedezzab, @antonioan, @im-Kitsch, @mthramann, @fbartolic, @rgallardone, @frrad, @jonnyhyman, @jennydaman, @likewei92, @acec2127, @rudimichal, @woutdenolf, @PauloHMTeixeira.
<sup>left: @beartype. right: you. why is it always like this?</sup>
@beartype users who discover security vulnerabilities are invited to privately disclose those vulnerabilities by submitting a GitHub-managed security…
@beartype is proud as a cub gnawing its first salmon to announce: @beartype has been Tidelifted! For our security-conscious corporate and government userbase, the best way to secure your enterprise and support @beartype is now through Tidelift vis-a-vis a SonarQube Advanced Security subscription. More on that later. We now return to your regularly scheduled release party. DJ Leycec in residence. Hit those fat QA jams.
Beartype 0.22.0 0.22.1 portals into the mortal plenum with a disturbing "WHOOOMP!" As you panic, all the oxygen in the room is rapidly vacuumed into an adjacent hyperdimension. It's not @beartype's safest entrance – but it's one we're all sure to remember. This is @beartype 0.22.1: don't ask what happened to 0.22.0. just... don't.
pip install --upgrade --pre beartype # beartype casts magic missile on the darknessThe central dogma of @beartype 0.22.1 is LLM compatibility. Do you like LLM? Do you like compatibility? Then your code likes @beartype 0.22.1 (even against your better judgement). But before the liking starts...
@beartype 0.22.1 salutes you who are about to code
@leycec and his beautiful science wife are eating well. Thanks entirely to...
This release comes courtesy these proud GitHub Sponsors, without whom @leycec's cats would currently be eating grasshoppers in the abandoned back lot again:
Additional financial shout-outs to @ilyapoz (@Ilia Pozhilov), the amazing former Yandex code cosmonaut who graciously donated a pile of Georgian lari to @beartype this go-around. Apparently, the lari is denominated in the ლ Unicode character. What a symbol! It looks like a beautiful hat. If only the Canadian dollar was half as manly. 😭
Thanks so much, masters of fintech and Yandex.
The Masters of Fintech and Yandex. That's who.
This release also comes courtesy Tidelift, which very graciously pays out recurring income to security-sensitive open-source projects like @beartype, NumPy, and other stuff you probably care about. @beartype joining Tidelift has super-positive implications for Python's broader QA community – including:
If you represent a security-conscious corporate, government, or non-profit, the best way bar none for you to support @beartype and secure your own workflow is by subscribing to Tidelift through SonarQube Advanced Security. Security giant Sonar recently acquired Tidelift, guaranteeing the economic viability of the Tidelift model for billions of future open-source projects that have yet to be born. Join the jargon-laden conversation and pay someone else to think about unreadable acronyms like SAST, SCA, and SBOM for once.
Pictured: Artistic rendition of the @beartype development process before Tidelift. You weren't supposed to see this.
You really want to bump the @beartype requirement in your pyproject.toml file. Preserve end user sanity tomorrow by explicitly requiring a minimum of @beartype >=0.22.1 today: e.g.,
# In your top-level "pyproject.toml" configuration:
dependencies = [
...
"beartype >=0.22.1", # <-- once you go 0.22.1, you go 0.22.1 for life
...
]Why? Bear with us. This explanation may bore you. Imagine what typing this out felt like.
Prior versions of @beartype are fundamentally incompatible with Python 3.14. Python packagers like pip and uv do not update packages by default. Unless you bump your @beartype requirement, your existing userbase who already installed your package will be unable to use your package under Python 3.14 – even after manually updating your package, because manually updating your package fails to transitively update all dependencies of your package by default. In other words, Python packaging still kinda sucks.
This is why...
@beartype looks stoically into the wind as everything breaks
beartype.claw import hooks have been supremely revamped. They still work the same, but they're now explicitly compatible with a lot more than they used to be. If you tried enabling beartype_this_package() but switched back to manually decorating everything with @beartype because beartype_this_package() spewed too many errors everywhere, please give beartype_this_package() a second chance:
# In the "{your_package}.__init__" submodule:
from beartype.claw import beartype_this_package
beartype_this_package() # <-- we're willing to swear on our pinkies that this works nowLet us know how it goes. If stuff is still busted, we'll immediately fix that stuff. We now have the necessary machinery in our abstract syntax tree (AST) transformer to support all (or most, anyway) compatibility woes previously associated with beartype.claw import hooks.
the new beartype.claw shamelessly dances for anyone
@beartype 0.22.1 dramatically improves compatibility across the board with the APIs, packages, and paradigms you care about. Because you care, we care. In fact, we spent whole months caring. We cared so much we're all cared out. The summer went away in a blitz of caring and we didn't even notice. Oh, Gods. The warmth has fled. The snow is coming. And all we have to show for it is massive compatibility gains across the board.
This includes:
@beartype 0.22.1 weeps from pride and accomplishment, but mostly sleep deprivation
Python 3.14. You care about Python 3.14 even if you don't know you care. @beartype now fully supports PEP 649 and 749 – landmark QA standards introduced by Python 3.14 that finally obsolete PEP 563. All these numbers mean something. We swear. Since all horror stories start with two nondescript teens in a Buick, let's start there:
from __future__ import annotationsThat's PEP 563. And... that's now deprecated. PEP 749 officially deprecated PEP 563 a few months ago:
Sometime after the last release that did not support PEP 649 semantics (expected to be 3.13) reaches its end-of-life,
from __future__ import annotationsis deprecated. Compiling any code that uses the future import will emit a DeprecationWarning. This will happen no sooner than the first release after Python 3.13 reaches its end-of-life, but the community may decide to wait longer.
After at least two releases, the future import is removed, and annotations are always evaluated as per PEP 649. Code that continues to use the future import will raise aSyntaxError, similar to any other undefined future import.
tl;dr: On October ~15th 2029, from __future__ import annotations will be officially deprecated. On October ~15th 2031, from __future__ import annotations will be removed entirely from the Python language. At that time, any module using from __future__ import annotations will raise a SyntaxError at importation time and thus become unimportable. In 2025, nobody should enable from __future__ import annotations voluntarily.
Sometime over the next several five years, you and your righteous dev team will require Python ≥ 3.14 as a mandatory dependency. That's just the way of the Python world. Planned obsolesce is the road we walk. When that happens, you'll no longer need from __future__ import annotations to declare forward references to undefined types in type hints like this:
# Look, Ma! No "from __future__ import annotations".
# We don't need the future where we're going.
from beartype import beartype
# Under Python ≥ 3.14, this just works. You annotated a function as accepting
# an instance of a type you haven't even declared yet. Yet, this is now fine.
# @beartype accepts you and your suspicious code for you who are.
@beartype
def useless_func(forward_reference_to_undefined_type: ThisJustWorksNow) -> ThisJustWorksNow:
return forward_reference_to_undefined_type
# Of course, you *DO* have to eventually define the undefined type used above.
# If you don't, everything will still blow up. It's not @beartype's fault.
# Python 3.14 made us do it... We blame Guido.
class ThisJustWorksNow(object):
passUnquoted forward references are thus baked into Python 3.14. Order of type hints and types is no longer significant. Define and annotate stuff in any order you like.
@beartype 0.22.1: because life is too short and code is too long.
@beartype: always ready to rip its shirt off at the slightest provocation
@beartype 0.22.1 now ships with out-of-the-box support for Bad Boy LLM APIs that defy community standards, mental health, and your last hair follicles. This includes:
These APIs are awesome, because they changed the world. But they're also hostile to literally every other Python decorator in existence. @beartype is a Python decorator in existence. Thus, these APIs are hostile to @beartype.
Why? Because they all define decorator-hostile decorators: that is, decorators that prevent other decorators from being applied. That's not how decorators are supposed to work. You're supposed to be able to apply decorators in any arbitrary order. That was the deal, LLM APIs! Apparently, LLM APIs hated that deal. Their decorators destructively transform your normal functions and methods (which are decoratable by @beartype) into abnormal instances of API-specific types (which are not decoratable by @beartype).
In the worst case of both LangChain and FastMCP, these abnormal instances of API-specific types aren't even callable! They don't just destroy the types of what they decorate. They destroy the callability of what they decorate. What kind of compatibility-hostile API turns a function or method into an uncallable object that you can't do anything with anymore? LangChain and FastMCP. That's who.
Examples include:
@langchain_core.runnables.chain decorator function.@fastmcp.FastMCP.tool decorator method.@celery.Celery.task decorator method.@beartype 0.22.1 now officially supports decorator-hostile decorators like this. It cost us our summer, but no price is too high. Okay. The price was pretty high. But this is the AI-ML-LLM hype train we're talking about. You either board that train or you prepare to eat everybody else's dust as they point fingers and cruelly guffaw into their monocles at you. @beartype prefers to board that train.
@beartype walks its own road, though. @beartype boards that train in its own special way. Specifically, @beartype now maintains two internal databases efficiently structured as trie prefix search trees:
beartype.claw import hooks then:
@beartype decorator before (rather than after) the last decorator-hostile decorator in existing chains of two or more consecutive decorators decorating your callables and types in your modules.@beartype decorator now silently ignores attempts to decorate instances of these problematic types. Don't even bother! They're busted, @beartype. At least we no longer are. 😅It's... complicated. Really, really complicated. There's a doctoral PhD thesis somewhere here for somebody who wants one. Me? I just wanna sleep. Blessed sleep! Take me now!
left: @beartype. right: langchain, fastmcp, and celery. you think we forgive you that easily!?
Polars is the vibrant Pandas alternative everyone loves. 35k GitHub stars cannot be wrong. Although I feel jealousy when I hear numbers like that, @beartype now officially supports validation of Polars DataFrames vis-a-vis Pandera – the only sane way to validate the integrity of your fragile DataFrames that are probably falling over as we speak. Poor guys.
Previously, @beartype only supported validation of Pandas DataFrames via Pandera. Now, @beartype supports both Pandas and Polars. This can only mean one thing. Our powers are growing at an exponential rate. The QA Singularity is upon us. Check out this terrifying exhibition of runtime validation run amok:
import pandera.polars as papol
import beartype
import pandera.typing.polars as pt
import polars as pl
class Schema(papol.DataFrameModel):
state: str
city: str
price: int = papol.Field(in_range={"min_value": 5, "max_value": 20})
@papol.check_types
@beartype.beartype
def test_schema(df: pl.DataFrame) -> pt.DataFrame[Schema]:
return df
df = pl.DataFrame({
"state": ["Ohio", "Ohio", "Ohio", "Nevada", "Nevada"],
"city": ["Youngstown", "Akron", "Columbus", "Reno", "Las Vegas"],
"price": [10, 20, 15, 14, 4]
# ^-- *VIOLATION*. so bad. so very bad. we're panicking. game over, man!
})
test_schema(df)...which helpfully blows up with a human-readable exception that relieves you:
Traceback (most recent call last):
File "/home/leycec/tmp/mopy.py", line 24, in <module>
test_schema(df)
~~~~~~~~~~~^^^^
File "/home/leycec/py/pyenv/versions/3.13.2/lib/python3.13/site-packages/pandera/decorators.py", line 841, in _wrapper
return _check_arg("return", out)
File "/home/leycec/py/pyenv/versions/3.13.2/lib/python3.13/site-packages/pandera/decorators.py", line 722, in _check_arg
raise error_handler.schema_errors[0]
pandera.errors.SchemaError: error in check_types decorator of function 'test_schema':
Column 'price' failed validator number 0: <Check in_range: in_range(5, 20)> failure case
examples: [{'price': 4}]@beartype: Bleeding-edge APIs named after magnetic dipoles? Yeah. We do that, too.
@beartype 0.22.1 pours one out for the DataFrame that didn't make it.
@beartype 0.22.1 fully supports PEP 646 – Variadic Generics. ...for certain glib definitions of "fully supports."
PEP 646 is outrageously huge. It's the longest and cruelest typing standard published to date. Synopsizing that standard is a fool's errand. Thus, we now synopsize that standard. PEP 646 brings two things to the QA table. Let's go!
I-I-Is that @beartype's arm she's holding up!? 😮
PEP 646 introduces type variable tuples (i.e., typing.TypeVarTuple(...) objects). Whereas good ol' PEP 484-compliant type variables (i.e., typing.TypeVar(...) objects) match only a single type (like MuhGeneric[int] for class MuhGeneric[T](): ...), type variable tuples greedily match zero or more types (like WoahGeneric[int, str, bool] for class WoahGeneric[*Ts](): ...).
The use case is tensors, supposedly. I personally press "F" to doubt that any real-world tensor frameworks will actually leverage type variable tuples. Doing so would inhibit forward compatibility with future tensor APIs in those frameworks. Why? Because type variable tuples match types greedily. Once you've exposed a type variable tuple to your end users through a public-facing generic type, you can never add any other type variables to that generic type without breaking backward compatibility. You're now permanently locked in to that generic type API for the rest of all time.
Aren't ordinary type variables like that too, though? No. You can always add additional type variables to normal generic types without breaking backward compatibility. How? PEP 696-compliant type variable defaults (e.g., T = TypeVar("T", default=int)). Press "F" if anyone would like me to babble incoherently more about all this.
That said, type variable tuples probably do have practical internal use. I'd never expose them to end users for the aforementioned reasons. They cause compatibility woes. Still, @beartype 0.22.1 now fully supports them. Use them! Reassure us that we didn't waste the entire summer on this! Oh, Gods... the summer... it's... it's gone, everybody. 😩
@beartype 0.22.1 when it realized where the summer went
PEP 646 also introduces tuple type hint unpacking (e.g., tuple[int, *tuple[str, ...]]). This spec goes really hard really fast. The syntax is also kinda nasty. But the core idea is that you can now deeply type-check the contents of non-trivial tuple data structures. You may now be thinking:
"Uhh... wat? Tuple data structures? Can you even use tuples like data structures? Even if you can, should you? Wouldn't a tuple data structure promote unreadable and obfuscated code that not even the unpaid intern wants to maintain?"
Indeed! It's all true! You can use tuples like data structures. @beartype internally does this all the time. Why? Unjustifiable microoptimizations. Because CPython is highly internally optimized for tuple instantiation, access, and garbage-collection, tuples make the ideal read-only data structures for many perfidious purposes. CPython cares a lot about tuples. Tuples are the backbone of CPython's calling convention, because functions and methods returning multiple values implicitly return tuples of those values. This makes tuples the ideal data structures for implementing many pure-Python algorithms – especially recursive algorithms implemented iteratively.
Of course, tuple data structures do promote unreadable and obfuscated code that not even the unpaid intern wants to maintain. But that's not a problem if you're a dodgy codebase like @beartype. Ain't nobody maintaining this code except @leycec – a well-known glutton for punishment-by-dev-hell.
If you are like @leycec, you too can now type-check your shamefully growing heap of tuple data structures from Hell. How? PEP 646, yo. Previously, PEP 484 only let you type-check two simplistic kinds of tuple hints:
tuple[str, int], for example, is the fixed tuple hint matching tuples containing one string item followed by an integer item.tuple[str, ...], for example, is the variadic tuple hint matching tuples containing zero or more string items.That's great if your tuple data structures are simplistic. But they're probably not, are they? That's why you're still reading this at 4:17AM. Your wife is calling out for you in her fitful sleep, but you don't even care! This is riveting Internet reading right here!
So what if your tuple data structures are as complicated as your marriage? You reach for PEP 646 and @beartype 0.22.1. You can now unpack at most one child tuple hint inside another parent tuple hint. For reasons that will become clear shortly, most child tuple hints unpacked in this way are variadic. Do that and you've now defined a mixed fixed-variadic tuple hint that matches tuples containing (in order):
tuple[str, bytes, *tuple[int, ...], bool, float], for example, is the mixed fixed-variadic tuple hint matching tuples containing (in order) a string item, a byte string item, zero or more integer items, a boolean item, and a floating-point number item. Cool, right? But the coolness doesn't stop there. Consider cardinality. Old-school variadic tuple hints (like tuple[str, ...]) only match tuples containing zero or more items. But what if you want to match a positive number of items? Tuple hint unpacking trivially lets you do that, too.
tuple[str, *tuple[str, ...]], for example, is the mixed fixed-variadic tuple hint matching tuples containing one or more strings. This example then generalizes to arbitrary cardinality bound only by your patience and openness to syntactic barbarism. Want to match tuples containing a larger number of strings? Just keep prepending str child type hints until you're satisfied, exhausted, and dripping with sweat at 4:17AM.
tuple[str, str, str, str, str, *tuple[str, ...]], for example, is the mixed fixed-variadic tuple hint matching tuples containing five or more strings. It's silly. Yet, it works. Kinda.
@beartype 0.22.1: it's only silly if you admit it's silly.
beartype 0.22.1 proudly unpacks tuple hints as the wind blows its hair around
...to financially feed @leycec and his friendly @beartype through either:
Cue hypnagogic rave music that encourages fiscal irresponsibility. 🎵 🎹 🎶
@beartype high-fives the reclusive secret society of worldwide bear bros who might possibly care about this. You are the select few. The elect enlightened. You are:
@posita, @wesselb, @tusharsadhwani, @JWCS, @patrick-kidger, @EtaoinWu, @iamrecursion, @Moosems, @langfield, @sylvorg, @Glinte, @cclauss, @sean-roelofs-ai, @kultura-luke, @jonathanberthias, @gotmax23, @adamtheturtle, @ilyapoz, @MilesCranmer, @rg936672, @ddorian, @k4ml, @riesentoaster, @LeonHilf, @jeertmans, @mzealey, @thetianshuhuang, @RomainBrault, @alisaifee, @ArneBachmannDLR, @JelleZijlstra, @tactile-metrology, @RobPasMue, @GithubCamouflaged, @kloczek, @uriyasama, @danielgafni, @JWCS, @rbroderi, @AlanCoding, @tvdboom, @crypdick, @jvesely, @komodovaran, @kaparoo, @MaximilienLC, @fleimgruber, @alexoshin, @gabrieldemarmiesse, @James4Ever0, @NLPShenanigans, @rtbs-dev, @yurivict,
Note truncated.
That's [PEP 563][]. And... that's now deprecated. PEP 749 officially deprecated PEP 563 a few months ago:
Beartype 0.22.0 Release Candidate 0 portals into the mortal plenum with a disturbing "WHOOOMP!" As you panic, all the oxygen in the room is rapidly vacuumed into an adjacent hyperdimension. It's not @beartype's safest entrance – but it's one we're all sure to remember. This is @beartype 0.22.0rc0:
pip install --upgrade --pre beartype # beartype casts magic missile on the darkness
The central dogma of @beartype 0.22.0rc0 is LLM compatibility. Do you like LLM? Do you like compatibility? Then your code likes @beartype 0.22.0rc0 (even against your better judgement). But before the liking starts...
<sup>@beartype 0.22.0rc0 salutes you who are about to code</sup>
@leycec and his beautiful science wife are eating well. Thanks entirely to...
This release comes courtesy these proud GitHub Sponsors, without whom @leycec's cats would currently be eating grasshoppers in the abandoned back lot again:
Additional financial shout-outs to @ilyapoz (@Ilia Pozhilov), the amazing former Yandex code cosmonaut who graciously donated a pile of Georgian lari to @beartype this go-around. Apparently, the lari is denominated in the ლ Unicode character. What a symbol! It looks like a beautiful hat. If only the Canadian dollar was half as manly. :sob:
Thanks so much, masters of fintech and Yandex.
<sup>The Masters of Fintech and Yandex. That's who.</sup>
You really want to bump the @beartype requirement in your pyproject.toml file. Preserve end user sanity tomorrow by explicitly requiring a minimum of @beartype >=0.22.0rc0 today: e.g.,
# In your top-level "pyproject.toml" configuration:
dependencies = [
...
"beartype >=0.22.0rc0", # <-- once you go 0.22.0, you go 0.22.0 for life
...
]
Why? Bear with us. This explanation may bore you. Imagine what typing this out felt like.
Prior versions of @beartype are fundamentally incompatible with Python 3.14. Python packagers like pip and uv do not update packages by default. Unless you bump your @beartype requirement, your existing userbase who already installed your package will be unable to use your package under Python 3.14 – even after manually updating your package, because manually updating your package fails to transitively update all dependencies of your package by default. In other words, Python packaging still kinda sucks.
This is why...
<sup>@beartype looks stoically into the wind as everything breaks</sup>
beartype.claw import hooks have been supremely revamped. They still work the same, but they're now explicitly compatible with a lot more than they used to be. If you tried enabling beartype_this_package() but switched back to manually decorating everything with @beartype because beartype_this_package() spewed too many errors everywhere, please give beartype_this_package() a second chance:
# In the "{your_package}.__init__" submodule:
from beartype.claw import beartype_this_package
beartype_this_package() # <-- we're willing to swear on our pinkies that this works now
Let us know how it goes. If stuff is still busted, we'll immediately fix that stuff. We now have the necessary machinery in our abstract syntax tree (AST) transformer to support all (or most, anyway) compatibility woes previously associated with beartype.claw import hooks.
<sup>the new beartype.claw shamelessly dances for anyone</sup>
@beartype 0.22.0rc0 dramatically improves compatibility across the board with the APIs, packages, and paradigms you care about. Because you care, we care. In fact, we spent whole months caring. We cared so much we're all cared out. The summer went away in a blitz of caring and we didn't even notice. Oh, Gods. The warmth has fled. The snow is coming. And all we have to show for it is massive compatibility gains across the board.
This includes:
<sup>@beartype 0.22.0rc0 weeps from pride and accomplishment, but mostly sleep deprivation</sup>
Python 3.14. You care about Python 3.14 even if you don't know you care. @beartype now fully supports PEP 649 and 749 – landmark QA standards introduced by Python 3.14 that finally obsolete PEP 563. All these numbers mean something. We swear. Since all horror stories start with two nondescript teens in a Buick, let's start there:
from __future__ import annotations
That's PEP 563. And... that's now deprecated. PEP 749 officially deprecated PEP 563 a few months ago:
Sometime after the last release that did not support PEP 649 semantics (expected to be 3.13) reaches its end-of-life,
from __future__ import annotationsis deprecated. Compiling any code that uses the future import will emit a DeprecationWarning. This will happen no sooner than the first release after Python 3.13 reaches its end-of-life, but the community may decide to wait longer. After at least two releases, the future import is removed, and annotations are always evaluated as per PEP 649. Code that continues to use the future import will raise aSyntaxError, similar to any other undefined future import.
tl;dr: On October ~15th 2029, from __future__ import annotations will be officially deprecated. On October ~15th 2031, from __future__ import annotations will be removed entirely from the Python language. At that time, any module using from __future__ import annotations will raise a SyntaxError at importation time and thus become unimportable. In 2025, nobody should enable from __future__ import annotations voluntarily.
Sometime over the next several five years, you and your righteous dev team will require Python ≥ 3.14 as a mandatory dependency. That's just the way of the Python world. Planned obsolesce is the road we walk. When that happens, you'll no longer need from __future__ import annotations to declare forward references to undefined types in type hints like this:
# Look, Ma! No "from __future__ import annotations".
# We don't need the future where we're going.
from beartype import beartype
# Under Python ≥ 3.14, this just works. You annotated a function as accepting
# an instance of a type you haven't even declared yet. Yet, this is now fine.
# @beartype accepts you and your suspicious code for you who are.
@beartype
def useless_func(forward_reference_to_undefined_type: ThisJustWorksNow) -> ThisJustWorksNow:
return forward_reference_to_undefined_type
# Of course, you *DO* have to eventually define the undefined type used above.
# If you don't, everything will still blow up. It's not @beartype's fault.
# Python 3.14 made us do it... We blame Guido.
class ThisJustWorksNow(object):
pass
Unquoted forward references are thus baked into Python 3.14. Order of type hints and types is no longer significant. Define and annotate stuff in any order you like.
@beartype 0.22.0rc0: because life is too short and code is too long.
<sup>@beartype: always ready to rip its shirt off at the slightest provocation</sup>
@beartype 0.22.0rc0 now ships with out-of-the-box support for Bad Boy LLM APIs that defy community standards, mental health, and your last hair follicles. This includes:
These APIs are awesome, because they changed the world. But they're also hostile to literally every other Python decorator in existence. @beartype is a Python decorator in existence. Thus, these APIs are hostile to @beartype.
Why? Because they all define decorator-hostile decorators: that is, decorators that prevent other decorators from being applied. That's not how decorators are supposed to work. You're supposed to be able to apply decorators in any arbitrary order. That was the deal, LLM APIs! Apparently, LLM APIs hated that deal. Their decorators destructively transform your normal functions and methods (which are decoratable by @beartype) into abnormal instances of API-specific types (which are not decoratable by @beartype).
In the worst case of both LangChain and FastMCP, these abnormal instances of API-specific types aren't even callable! They don't just destroy the types of what they decorate. They destroy the callability of what they decorate. What kind of compatibility-hostile API turns a function or method into an uncallable object that you can't do anything with anymore? LangChain and FastMCP. That's who.
Examples include:
@langchain_core.runnables.chain decorator function.@fastmcp.FastMCP.tool decorator method.@celery.Celery.task decorator method.@beartype 0.22.0rc0 now officially supports decorator-hostile decorators like this. It cost us our summer, but no price is too high. Okay. The price was pretty high. But this is the AI-ML-LLM hype train we're talking about. You either board that train or you prepare to eat everybody else's dust as they point fingers and cruelly guffaw into their monocles at you. @beartype prefers to board that train.
@beartype walks its own road, though. @beartype boards that train in its own special way. Specifically, @beartype now maintains two internal databases efficiently structured as trie prefix search trees:
beartype.claw import hooks then:
@beartype decorator before (rather than after) the last decorator-hostile decorator in existing chains of two or more consecutive decorators decorating your callables and types in your modules.@beartype decorator now silently ignores attempts to decorate instances of these problematic types. Don't even bother! They're busted, @beartype. At least we no longer are. :sweat_smile:It's... complicated. Really, really complicated. There's a doctoral PhD thesis somewhere here for somebody who wants one. Me? I just wanna sleep. Blessed sleep! Take me now!
<sup>left: @beartype. right: langchain, fastmcp, and celery. you think we forgive you that easily!?</sup>
...to financially feed @leycec and his friendly @beartype through our ancient GitHub Sponsors profile that predates the existence of dinosaur-like AI chatbots. Come for the candid insider photos of a sordid and disreputable life in the Canadian interior; stay for the GitHub badge and warm feelings of general goodwill.
Cue hypnagogic rave music that encourages fiscal irresponsibility. :musical_note: :musical_keyboard: :notes:
@beartype high-fives the reclusive secret society of worldwide bear bros who might possibly care about this. You are the select few. The elect enlightened. You are:
@posita, @wesselb, @tusharsadhwani, @JWCS, @patrick-kidger, @EtaoinWu, @iamrecursion, @Moosems, @langfield, @sylvorg, @Glinte, @cclauss, @sean-roelofs-ai, @kultura-luke, @jonathanberthias, @gotmax23, @adamtheturtle, @ilyapoz, @MilesCranmer, @rg936672, @ddorian, and @k4ml.
<sup>left: @beartype. right: you. why is it always like this?</sup>
Beartype 0.21.0 consoles your codebase as it shudders under the oppressive tidal wave of bugs. Much like its predecessors, @beartype 0.21.0 is here to
Beartype 0.21.0 consoles your codebase as it shudders under the oppressive tidal wave of bugs. Much like its predecessors, @beartype 0.21.0 is here to help. Unlike its predecessors, @beartype 0.21.0 claims it solves more problems than it creates for once. Is @beartype 0.21.0.... lying!? :face_with_open_eyes_and_hand_over_mouth:
pip install --upgrade beartype # <-- blast all bugs into the git pit
Let your test suite show the truth – even if @leycec just wants to play obscure French video games with titles like Clair Obscur: Expedition 33 (Because This Couldn't Be More Pretentiously Pseudorandom) the entire weekend and pretend our issue tracker isn't collapsing under its own ponderous weight:
<sup>@beartype 0.21.0: this can't be what you've waited months for</sup>
@beartype 0.21.0 is gratefully brought to you by...
This release comes courtesy these proud GitHub Sponsors, without whom @leycec's cats would currently be eating grasshoppers:
Thanks so much, masters of fintech.
<sup>The Masters of Fintech and Metrology. That's who.</sup>
Let's get this pawful party started.
@beartype 0.21.0 is obsessed with recursive data structures. They're more common than you might think! Okay. They're totally rare. We all learn about recursive data structures as poverty-stricken undergrads who subsist on years-old cup ramen and then pretend we never learned about them. You'll never need to implement a recursive data structure in pure-Python, because somebody else already did that for you. Graphs, heaps, queues, linked lists, skip lists, trees, and (our personal favourite) tries are all sufficiently awesome that you're already using most of them... because somebody else made them. That's why you're using them! Right? Ain't nobody got spare time or brain space to hack out a pure-Python red-black binary tree in 2025. But somebody did.
@beartype 0.21.0 is for that somebody. When you need recursion, you need @beartype 0.21.0.
@beartype 0.21.0 also acknowledges that 2025 is Humanity on Hard Mode™. The planet isn't doing well. Humanity isn't doing well. Industrial civilization isn't doing well. The US isn't doing well. Even Canada's looking a bit shaky – and we face literal death just by going outside six months of the year. Let's not even mention the deer flies, black flies, mosquitos, ticks, or rabid raccoons. Gods. Anything but the rabid raccoons. Therefore, wherever you are, whatever you face, whenever the darkness erupts and starts gnawing on your codebase...
@beartype 0.21.0 will be there. We got your codebase's back. In fact, we're currently scratching that back. Feels good, right? These paws have claws – but only for bugs. Your code got lucky.
<sup>@beartype 0.21.0: a familiar face you can trust</sup>
Let @beartype assuage, massage, and presage <sup>...wat? it's my release party and i'll rhyme if i wanna</sup> those issues away. @beartype 0.21.0 promises it delivers first-class best-of-breed hyphenated-jargon-hype-train support for:
Recursive type hints! That's right. Now you too can revel in the disgusting power of infinitely deep data structures with PEP 695-compliant recursive type aliases. The only catch? This unworldly magic needs Python ≥ 3.12, which is quite the catch indeed. Behold! Unworldly magic:
# Type hint matching an infinitely recursive list. Look, I don't know. This is for
# the extreme sports coders that like to live dangerously and code even harder.
type RecursiveListExplodesYourApp = list[RecursiveListExplodesYourApp]
Opt-in dataclass field checking! That's right. Now you too can type-check @dataclass fields on assignment by enabling is_pep557_fields=True – much to the dismay of everybody else in the office. The only catch? Actually, there are multiple catches. No relative forward references and no PEP 563 support means no from __future__ import annotations. That's why dataclass field checking remains disabled by default. You have to opt in, because the best things in life are dangerous and reckless and hurt a lot. Like, a lot a lot:
# @beartype: It might not be Pydantic, but at least it cost you nothing.
beartype_this_package(conf=BeartypeConf(is_pep557_fields=True)) # <-- magical explosions?
Generalized hint overrides! That's right. Now you too can replace all list[str] type hints with... uhh, list[str] | tuple[str, ...]. Pretend somebody wants this:
# Users can now pass tuples of strings to all callables annotated as
# accepting only lists of strings. waaaaaaaaaaaaaaaaaaaaaaaaaaaaaaat?
beartype_this_package(conf=BeartypeConf(hint_overrides=FrozenDict({
list[str]: list[str] | tuple[str, ...]}))) # <-- pretend this makes sense
Frozen dictionaries! It's happening, because beartype.FrozenDict is making it happen:
from beartype import FrozenDict
# Finally, a set of frozen dictionaries! Yes, it's all true. Now you too can use
# dictionaries as dictionaries keys or set members. Why? Because you can.
freezing_my_dict_off = {
FrozenDict({'My ganglia!': 'It hurts.'}),
FrozenDict({'What even is a ganglia?': 'No idea. But it surely hurts.'}),
}
Probably other stuff! But nobody cares, because nobody even read this far. WAIT. You're reading this far. Clearly, you're somebody – somebody awesome who actually has hair and is profoundly changing the world! It only goes to show you can't believe anything you read in a changelog anymore. 2025: "So even the changelogs lie now, huh?"
<sup>@beartype 0.21.0: If you don't feel like a wild animal while coding, can it be called coding?</sup>
@beartype 0.21.0 now officially supports all possible forms of recursion in type hints. This includes directly recursive PEP 695 type aliases, indirectly recursive PEP 484 generics, and @beartype-specific hint overrides. Which you prefer depends on which bitter pill you're willing to swallow:
If you're willing to require Python ≥ 3.12 as a mandatory dependency, prefer PEP 695 type aliases. They're concise. They're descriptive. They're elegant. They "just work" intuitively in the exact way you expect them to:
# Annotate recursive data structures with a "simple" one-liner. \o/
type RecursiveListExplodesYourApp = list[RecursiveListExplodesYourApp]
If you're unwilling to require Python ≥ 3.12 as a mandatory dependency, fallback to PEP 484 self-subscripted generics. They're unconcise. They're non-descriptive. They're inelegant. They require heavy lifting on your part before they start working. But they do work under Python ≥ 3.9, which is more than we can say for PEP 695:
# One line that makes sense (above) or five lines that don't make sense (below)?
# Let the cat decide. ¯\_(ツ)_/¯
from typing import TypeVar
T = TypeVar('T')
class GenericList(list[T]):
pass
GenericRecursiveListExplodesYourApp = GenericList[GenericList]
Let's take this one recursive app destroyer at a time.
<sup>@beartype 0.21.0: this is the biggest animated gif i have ever seen</sup>
Directly recursive PEP 695 type aliases is what everybody who wants recursive type hints wants. Against all odds, you're actually reading this. You want recursive type hints. Thus, you want:
# Type hint matching an infinitely recursive list. Look, I don't know. This is for
# the extreme sports coders that like to live dangerously and code even harder.
type RecursiveListExplodesYourApp = list[RecursiveListExplodesYourApp]
# @beartype now type-checks this infinitely recursive list in O(1) time. Of
# course, that's impossible. But @beartype doesn't even care anymore! F- it!
from beartype import beartype
@beartype
def dangerous_func_means_well(oh_gods: RecursiveListExplodesYourApp) -> None:
'''
Dangerous function iteratively recurses into the passed infinitely recursive
list until either bottoming out at the same list... *or blowing up.*
Which do you hope happens first?
'''
# The growing terror you feel just speed-reading this code is real.
seen_horror_ids: set[int] = set()
unseen_horrors: list[RecursiveListExplodesYourApp] = list((oh_gods,))
# Recurse into that terror. Recurse until your face is numb, like mine.
while unseen_horrors:
# Pop that terror like a meat balloon. If it squishes, you must pop it.
seen_horror = unseen_horrors.pop()
print(f'Visiting infinitely recursive list: {id(seen_horror)}')
# Awaken from this logic nightmare, gentle reader!
if id(seen_horror) in seen_horror_ids:
print("Recursion detected! We're outta here, suckers!")
break
# Pretend this does what the docstring says this does. *gulp*
seen_horror_ids.add(id(seen_horror))
unseen_horrors.append(seen_horror[0])
# Infinitely recursive list. If you try this in the office, you may regret the
# fateful day your career decisions plummeted down a cliff.
OH_GODS = []
OH_GODS.append(OH_GODS)
# Pass this function valid input. Stare down the infinitely recursive list?
# Don't mind if I do! Gape in awe before infinity blows up your call stack.
dangerous_func_means_well(OH_GODS)
# Pass this function invalid input. No! No! Gods! NOOOOOOOOOOOOOOOOOOOOOOO!
dangerous_func_means_well(['Open-source', 'sells,' 'but', "who's", 'buying?'])
...which raises the expected output and exception traceback:
Visiting infinitely recursive list: 133179499204736
Visiting infinitely recursive list: 133179499204736
Recursion detected! We're outta here, suckers!
Traceback (most recent call last):
File "/home/leycec/tmp/mopy.py", line 48, in <module>
dangerous_func_means_well(['Open-source', 'sells,' 'but', "who's", 'buying?'])
~~~~~~~~~~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "<@beartype(__main__.dangerous_func_means_well) at 0x792044b9c360>", line 40,
in dangerous_func_means_well
beartype.roar.BeartypeCallHintParamViolation: Function __main__.dangerous_func_means_well() parameter oh_gods=['Open-source', 'sells,but',
"who's", 'buying?'] violates type hint RecursiveListExplodesYourApp, as list index 2
item str "who's" not instance of list.
Pore one out for the unsuspecting @beartype users that actually tried to run the above example. Their smoking CPUs are no longer with us. What remains of the ruin of their motherboards is now locked into a segfaulting bootloop featuring a cackling ASCII-art bear. It is sad.
<sup>@beartype 0.21.0: "zomg so cuuuuuute oh my brain hurts nooooooooooooooo"</sup>
What? Catch? Surely you jest! There's no... oh, who am I kidding. There are huge catches associated with PEP 695. For one, @beartype intentionally does not support older PEP-noncompliant variants of recursive type hints that used stringified forward references. You might occasionally see crufty stuff like this floating around StackOverflow, older codebases, or the mypy issue tracker:
HorrifyingRecursiveTypeHint = Union[str, 'HorrifyingRecursiveTypeHint']
@beartype doesn't support that. Using stringified forward references to induce recursion is non-standard. @beartype probably could support that, but there's not much point in supporting non-standards when standardized alternatives exist. That's why...
@beartype 0.21.0 only supports PEP 695: the only standard for defining recursive type hints. Everything else was just something mypy made up. Recursive type aliases now work wonderfully under Python ≥ 3.12 – but that's the gotcha here.
<sup>@beartype 0.21.0: rambo with a sword is something that happened only on an alternate timeline... but it still happened</sup>
That's right. You love to hate it. PEP 695 is unusable under Python ≤ 3.11. Attempting to define any type alias under Python ≤ 3.11 results in CPython raising an unreadable "SyntaxError: invalid syntax" exception.
In a year or two, this will be significantly less of a hard blocker for everyone. Increasingly, nobody cares about Python ≤ 3.11. Do you care about Python ≤ 3.11? Maybe – but you probably shouldn't, unless your huge userbase is obsessed by Python ≤ 3.11. In that case, you're kinda screwed. You have to choose between your love for recursion and your love for having users. Tough choice. I'd choose recursion, personally.
<sup>beartype 0.21.0: users who hate recursion are users who make your face contort into a tight rictus of agony</sup>
Absolutely! Totally! How could anything else possibly go wrong!
...oh, who am I kidding!?!?!? There is yet another huge catch associated with PEP 695. @beartype does not deeply type-check recursive data structures to a countably infinite depth of nested recursion. Instead, @beartype:
Let's just accept this is happening. But why is this happening? Coupla reasons, fam:
O(1) time complexity. Deeply type-checking a recursive data structure with recursive height k would necessitate linear-time O(k) time complexity in @beartype – violating @beartype's fundamental efficiency guarantee.bad_list = []; bad_list.append(bad_list)). Of course, an iterative approach could be protected against these edge cases by dynamically generating type-checking code that maintains:
type alias to be type-checked, one set of the IDs of all previously type-checked objects. But now @beartype would need to allocate and append to one friggin' set for each recursive type alias for each function call. Space and time efficiency rapidly spirals into the gutter and then clutches its aching head like in a depressing Leaving Only Python ≥ 3.12!? Only one layer of recursion!?
<sup>@beartype 0.21.0: let's get sweaty, together</sup>
Let's assume you hate requiring Python ≥ 3.12. You still love Python 3.9, even though nobody else does. You walk your own dark road. In this case, you want...
Self-subscripting generics, huh? You may now be thinking:
"But what does that even mean? How can a generic subscript itself? What even are generics? What does "subscription" mean? What does anything mean in a post-modern world of fluid subjectivity?"
Continue reading as you walk your own dark road.
Two months ago, ostensible typing genius @EtaoinWu (Yue Wu) invented indirectly recursive type hints at #510. It probably wasn't even an accident. @EtaoinWu probably did it on purpose. Some people are like that. They just like smashing things with their brain hammers until something finally gives. This is that thing.
In the darkness of my man-lair, I realized that @EtaoinWu's approach can be generalized to create indirectly recursive type hints under Python ≤ 3.11. Since Python ≤ 3.11 fails to support PEP 695 recursive type aliases, it was previously believed that recursive type hints could only be "officially" created under Python ≥ 3.12.
Not so. By abusing PEP 484 or PEP 585 generics, you can actually create recursive type hints under Python ≤ 3.11. These hints are fully PEP-compliant. They're valid. They satisfy typing standards. Much like me, however, they're also super weird. You'll frown at them when you see them awkwardly shuffling past you on the sidewalk. You'll also have no choice but to use them if you want to type recursive data structures under Python ≤ 3.11.
To induce recursion without directly defining a PEP 695-compliant recursive type alias, "simply":
Behold! This is indirect recursion via self-subscripting generics:
CAUTION: Merely reading this code abomination could cause your sanity to slip even further into the yawning abyss off the coast of California known only as R'lyeh.
# Import boring stuff you've long grown to loathe. Kinda sad, actually.
# Shouldn't boilerplate like this spark joy instead? I agree.
from beartype import beartype
from typing import TypeVar
# Define a normal unbound type variable. Enjoy it. This is the last normal
# one-liner you will ever see.
T = TypeVar('T')
# Define a normal PEP 585-compliant generic parametrized by that variable. Still
# normal. Still sane. Feels good. Yet, that feeling of unspeakable horror...
class GenericList(list[T]):
pass
# Define a type hint subscripting that generic... *BY ITSELF!?*
#
# Indeed. This type hint, for example, matches an infinitely recursive list
# (i.e., a list such that all items of this list are also infinitely recursive
# lists of the same type).
IndirectlyRecursiveList = GenericList[GenericList]
@beartype
def destroy_the_universe(with_danger_list: IndirectlyRecursiveList) -> None:
'''
Prove that @beartype will let you destroy the universe, if only your
intentions are pure.
'''
print(with_danger_list)
# Define an infinitely recursive non-empty list satisfying this type hint.
super_danger_list = IndirectlyRecursiveList()
super_danger_list.append(super_danger_list)
# Prove that @beartype accepts your risky life choices.
destroy_the_universe(super_danger_list)
# Define a boring non-recursive non-empty list violating this type hint.
super_boring_list = IndirectlyRecursiveList([
'Super', 'boring', 'list', 'hates', 'fun.'])
# Prove that @beartype rejects your safe life choices.
destroy_the_universe(super_boring_list)
...which prints the expected output and exception traceback:
[[...]]
Traceback (most recent call last):
File "/home/leycec/tmp/mopy.py", line 45, in <module>
destroy_the_universe(super_boring_list)
~~~~~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^
File "<@beartype(__main__.destroy_the_universe) at 0x775b159d1440>", line 53, in destroy_the_universe
beartype.roar.BeartypeCallHintParamViolation: Function
__main__.destroy_the_universe() parameter
with_danger_list=['Super', 'boring', 'list', 'hates', 'fun.'] violates type hint
__main__.GenericList[__main__.GenericList], as generic superclass list[~T] of
<class "__main__.GenericList"> index 3 item str 'hates' not instance of
<class "__main__.GenericList">.
WOAH. The official repr() string for an infinitely recursive list generic is [[...]]. CPython just did that. We didn't do anything to make CPython do that. Somehow, that discovery is the coolest part of this whole changelog. I feel sad. :sob:
Voila! You've just created a recursive type hint that works under literally all Python versions – including Python ≤ 3.11. Nobody intended for anyone to do this. Thanks to the sickening force of the human mind, you can now do this.
Kinda surprised that nobody ever thought to subscript a generic by itself. Or did they!? Yeah... they probably did. But no @beartype users ever did that or somebody would have pounded their fists on our issue tracker about that. Or would they!? Yeah... they probably would. 😅 💦
<sup>@beartype 0.21.0: these tears i shed for your code are manly</sup>
No idea. I care in the abstract sense of the word "care." Computer science is a super-fun literary puzzle with real-world implications – which makes it even funner than "normal" puzzles, which are still fun but don't touch the real world in any meaningful way. The lolz. That's what I'm saying. I did this for the lolz.
If you're reading this from the comfort of your PodBed™ in the Year 2075, please know that I did everything I could to make your life better. I solved puzzles. I meant well. Now, future human (or human-like AI construct), my future is your grim struggle for daily sustenance wondrous present in a utopian dream-world.
May this small piece of the recursive puzzle assist you in your own puzzle-wrangling.
<sup>@beartype 0.21.0: because nobody tells you what to do anymore</sup>
Previously, @beartype hint overrides sorta but not really worked. Now, @beartype hint overrides actually do work for all possible use cases. Of course, I never got around to documenting hint overrides.
But don't let that sensible obstacle that should deter you deter you! Use undocumented APIs. Live a little. Let your dangling docstrings hang all out.
Lie to your userbase (and yourself) by globally replacing type hints without anyone's consent or knowledge. Not sure why anyone would want to behave like this, honestly. Therefore, @beartype allows you to behave like this. We support bad habits and so should you:
# Import tons of weirdo @beartype stuff. Look. I don't know either.
from beartype import beartype, BeartypeConf, FrozenDict
# Define a new @beartype decorator named @riskytype. Unlike @beartype, @riskytpe
# performs dangerous type hint overrides by replacing all "list[str]" type hints
# with "list[str] | tuple[str, ...]". Feels good. Users can now pass tuples of
# strings to all callables annotated as accepting only lists of strings. waaat?
riskytype = beartype(conf=BeartypeConf(hint_overrides=FrozenDict({
list[str]: list[str] | tuple[str, ...]})))
# Define a risky function decorated by @riskytype. *gulp*
@riskytype
def risky_func(risky_arg: list[str]) -> str:
return risky_arg[0]
# Prove that this function walks on the wild side.
print(risky_func(['This is fine.', 'You can tell because of my sweaty hand.']))
print(risky_func(('This is totally sus.', 'Users are panicking already.')))
# Prove that this function still occasionally behaves itself.
print(risky_func({'This is beyond sus...', '...where not even @beartype dares.'}))
...which prints the expected output and exception traceback:
This is fine.
This is totally sus.
Traceback (most recent call last):
File "/home/leycec/tmp/mopy.py", line 23, in <module>
print(risky_func({'This is beyond sus...', '...where not even @beartype dares.'}))
~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "<@beartype(__main__.risky_func) at 0x7370c39ce840>", line 48, in risky_func
beartype.roar.BeartypeCallHintParamViolation: Function __main__.risky_func()
parameter risky_arg={'This is beyond sus...', '...where not even @beartype dares.'}
violates type hint list[str], as set {'This is beyond sus...',
'...where not even @beartype dares.'} not list or tuple.
<sup>@beartype 0.21.0: when you feel the need to suck on a bottle in the darkness as an afro ninja looks on in shock</sup>
In the now-legendary GitHub poll "Tell @leycec What to Do", everybody told @leycec to type-check PEP 557 dataclass fields on assignment. Thus, @beartype 0.21.0 now type-checks dataclasses... sorta.
That's sorta right. Sorta means this mostly works, but might not. Type-checking dataclasses is hard. I am soft-bellied and lazy. After combining these adjectives, you get half-hearted dataclass type-checking.
@beartype only conditionally type-checks dataclass fields when you explicitly tell @beartype to type-check dataclass fields by enabling our newly introduced BeartypeConf(is_pep557_fields: bool = False) configuration option. For safety, this option is disabled by default. Ever since @beartype accidentally blew up PyTorch, your safety is our paramount concern. I can't have Microsoft breathing down my neckbeard again. Please! Not that...
When you want dataclass type-checking, you have to enable dataclass type-checking – like so:
# Import so many things you can barely see what matters anymore.
from beartype import beartype, BeartypeConf
from dataclasses import dataclass, InitVar
from typing import ClassVar
@beartype(conf=BeartypeConf(is_pep557_fields=True)) # <-- check it like a bear boss
@dataclass
class MuhDataclass(object):
muh_int: int
muh_classvar: ClassVar[str] = 'This is fine. Srsly. Does @leycec not have Buddha nature?'
muh_initvar: InitVar[bytes] = b'This is fine, too. No joke. No shade. No idea.'
# *GOOD.*
good_data = MuhDataclass(muh_int=42) # <-- this works
good_data.muh_int = 0xCAFEBABE # <------- this works, too
# *BAD.*
bad_data = MuhDataclass(muh_int=42) # <-- still works
bad_data.muh_int = '0xCAFEBABE' # <------ this fails! *YAY*!
...which raises the expected type-checking violation:
beartype.roar.BeartypeDecorHintParamDefaultViolation: Dataclass MuhDataclass(muh_int=42)
attribute 'muh_int' new value '0xCAFEBABE' violates type hint <class 'int'>,
as str '0xCAFEBABE' not instance of int.
As the above example demonstrates, this preliminary functionality supports cafe babes. Uhh... I mean, this supports:
@dataclass decorator passed no keyword parameters. :+1:@dataclass(frozen=True). :hand_with_index_finger_and_thumb_crossed:@dataclass(slots=True). :money_mouth_face:Truly, now you too can get Poor Man's Pydantic<sup>©</sup> for free from the comfort of your own AI-assisted keyboard while doing even less work than you ordinarily would while nursing a video game hangover on Sunday morning. @leycec did all the work for you and painfully regretted deeply cherished this character- and morale-building life lesson.
<sup>who did this to you, @beartype!?! oh, it was just dataclasses.</sup>
Thanks to the non-triviality of dataclasses and my own moral failings (read: "I am laziness incarnate"), this functionality currently fails to support all possible dataclass configurations and use cases. Popular edge cases not supported include:
Dataclass subclasses (i.e., dataclasses subclassing other dataclasses). This is completely untested. No idea what happens. Could blow up everything. Could do nothing, which is better than just blowing up everything.
PEP 563 (i.e., from __future__ import annotations), which almost certainly raises exceptions when enabling is_pep557_fields=True.
Dataclass fields annotated by one or more relative forward references (i.e., strings referring to the names of currently undefined types, subsequently defined in the current submodule), which almost certainly raises exceptions when enabling is_pep557_fields=True: e.g.,
from dataclasses import dataclass
@dataclass
class UnsupportedDataclass(object):
unsupported_field: 'UndefinedType' # <-- BREAKS EVERYTHING, YO
class UndefinedType(object): pass
Until @beartype fully supports all of the above edge cases, is_pep557_field will continue defaulting to False. Someday, this will surely work for everybody. Until then, let us collectively sob. 😭
<sup>@beartype 0.21.0: teach a dev to crush bugs for a day and he'll crush bugs for a life</sup>
Python needs an official frozendict implementation, if only to shut down continual demands for an official frozendict implementation. Thankfully, you use @beartype.
@beartype 0.21.0 now offers a public frozen dictionary type for you: beartype.FrozenDict! It actually works! It's mostly still C-based and thus fast! We tested everything and then some! We stuffed everything inside these things and they still pretended to work! We use frozen dictionaries everywhere in the @beartype codebase! Now, so can you!
beartype.FrozenDict: because Hell will freeze over before Python ever gets an official frozendict implementation.
from beartype import FrozenDict
# Finally, a set of frozen dictionaries! Yes, it's all true. Now you too can use
# dictionaries as dictionaries keys or set members. Why? Because you can.
freezing_my_dict_off = {
FrozenDict({'My ganglia!': 'It hurts.'}),
FrozenDict({'What even is a ganglia?': 'No idea. But it surely hurts.'}),
}
<sup>@beartype 0.21.0: we heard you wanted some FrozenDict with your FrozenDict</sup>
...to financially feed @leycec and his friendly @beartype through our ancient GitHub Sponsors profile that predates the existence of dinosaur-like AI chatbots. Come for the candid insider photos of a sordid and disreputable life in the Canadian interior; stay for the GitHub badge and warm feelings of general goodwill.
Cue hypnagogic rave music that encourages fiscal irresponsibility. :musical_note: :musical_keyboard: :notes:
@beartype high-fives the reclusive secret society of worldwide bear bros who might possibly care about this. You are the select few. The elect enlightened. You are:
@posita, @wesselb, @tusharsadhwani, @felix-hilden, @simonprovost, @JWCS, @patrick-kidger, @EtaoinWu, @iamrecursion, @Moosems, @langfield, @sylvorg, @mzealey, @thetianshuhuang, @RomainBrault, @ddorian, @rg936672, @alisaifee, @ArneBachmannDLR, @JelleZijlstra, @tactile-metrology, @RobPasMue, @GithubCamouflaged, @kloczek, @uriyasama, @danielgafni, @JWCS, @rbroderi, @AlanCoding, @tvdboom, @crypdick, @jvesely, @komodovaran, @kaparoo, @MaximilienLC, @fleimgruber, @alexoshin, @gabrieldemarmiesse, @James4Ever0, @NLPShenanigans, @rtbs-dev, @yurivict, @st--, @murphyk, @dosisod, @Rogdham, @alisaifee, @denisrosset, @damarro3, @ruancomelli, @jondequinor, @harshita-gupta, @jakebailey, @denballakh, @jaanli, @creatorrr, @msvensson222, @avolchek, @femtomc, @AdrienPensart, @jakelongo, @Artur-Galstyan, @ArneBachmann, @danielward27, @WeepingClown13, @rbnhd, @radomirgr, @rwiegan, @brettc, @spagdoon0411, @helderco, @paulwouters, @jamesbraza, @dcharatan, @kasium, @AdrienPensart, @sunildkumar, @peske, @mentalisttraceur, @awf, @PhilipVinc, @dcharatan, @empyrealapp, @rlkelly, @KyleKing, @skeggse, @RomainBrault, @deepyaman, @adamtheturtle, @minmax, @jedie, @pablovela5620, @thiswillbeyourgithub, @Logan-Pageler, @knyazer, @ilyapoz, @yuzhichang, @Fedezzab, @antonioan, @im-Kitsch, @mthramann, @fbartolic, @rgallardone, @frrad, @jonnyhyman, @jennydaman, @likewei92, @acec2127, @Glinte, @rudimichal, @woutdenolf, @PauloHMTeixeira.
The burden of QA is high – but you have chosen to carry the smelly torch. Keep that suspiciously purple flame alive! The recursive data structure you crush the bugs out of tonight may very well be your own.
<sup>@beartype 0.21.0 stands poetically before the burning wreckage of your competitor's codebase</sup>
Beartype 0.21.0 Release Candidate 0 consoles your codebase as it shudders under the oppressive tidal wave of bugs. Much like its predecessors, @bearty
Beartype 0.21.0 Release Candidate 0 consoles your codebase as it shudders under the oppressive tidal wave of bugs. Much like its predecessors, @beartype 0.21.0rc0 is here to help. Unlike its predecessors, @beartype 0.21.0rc0 claims it solves more problems than it creates for once. Is @beartype 0.21.0rc0.... lying!? :face_with_open_eyes_and_hand_over_mouth:
pip install --upgrade --pre beartype # <-- blast all bugs into the git pit
Let your test suite show the truth – even if @leycec just wants to play obscure French video games with titles like Clair Obscur: Expedition 33 (Because This Couldn't Be More Pretentiously Pseudorandom) the entire weekend and pretend our issue tracker isn't collapsing under its own ponderous weight:
<sup>@beartype 0.21.0rc0: this can't be what you've waited months for</sup>
@beartype 0.21.0rc0 is gratefully brought to you by...
This release comes courtesy these proud GitHub Sponsors, without whom @leycec's cats would currently be eating grasshoppers:
Thanks so much, masters of fintech and metrology.
<sup>The Masters of Fintech and Metrology. That's who.</sup>
Let's get this pawful party started.
@beartype 0.21.0rc0 is obsessed with recursive data structures. They're more common than you might think! Okay. They're totally rare. We all learn about recursive data structures as poverty-stricken undergrads who subsist on years-old cup ramen and then pretend we never learned about them. You'll never need to implement a recursive data structure in pure-Python, because somebody else already did that for you. Graphs, heaps, queues, linked lists, skip lists, trees, and (our personal favourite) tries are all sufficiently awesome that you're already using most of them... because somebody else made them. That's why you're using them! Right? Ain't nobody got spare time or brain space to hack out a pure-Python red-black binary tree in 2025. But somebody did.
@beartype 0.21.0rc0 is for that somebody. When you need recursion, you need @beartype 0.21.0rc0.
@beartype 0.21.0rc0 also acknowledges that 2025 is Humanity on Hard Mode™. The planet isn't doing well. Humanity isn't doing well. Industrial civilization isn't doing well. The US isn't doing well. Even Canada's looking a bit shaky – and we face literal death just by going outside six months of the year. Let's not even mention the deer flies, black flies, mosquitos, ticks, or rabid raccoons. Gods. Anything but the rabid raccoons. Therefore, wherever you are, whatever you face, whenever the darkness erupts and starts gnawing on your codebase...
@beartype 0.21.0rc0 will be there. We got your codebase's back. In fact, we're currently scratching that back. Feels good, right? These paws have claws – but only for bugs. Your code got lucky.
<sup>@beartype 0.21.0rc0: a familiar face you can trust</sup>
Let @beartype assuage, massage, and presage <sup>...wat? it's my release party and i'll rhyme if i wanna</sup> those issues away. @beartype 0.21.1rc0 promises it delivers first-class best-of-breed hyphenated-jargon-hype-train support for:
Recursive type hints! That's right. Now you too can revel in the disgusting power of infinitely deep data structures with PEP 695-compliant recursive type aliases:
# Type hint matching an infinitely recursive list. Look, I don't know. This is for
# the extreme sports coders that like to live dangerously and code even harder.
type RecursiveListExplodesYourApp = list[RecursiveListExplodesYourApp]
Opt-in dataclass field checking! That's right. Now you too can type-check @dataclass fields on assignment by enabling is_pep557_fields=True – much to the dismay of everybody else in the office:
# @beartype: It might not be Pydantic, but at least it cost you nothing.
beartype_this_package(conf=BeartypeConf(is_pep557_fields=True)) # <-- magical explosions?
Generalized hint overrides! That's right. Now you too can replace all list[str] type hints with... uhh, list[str] | tuple[str, ...]. Pretend somebody wants this:
# Users can now pass tuples of strings to all callables annotated as
# accepting only lists of strings. waaaaaaaaaaaaaaaaaaaaaaaaaaaaaaat?
beartype_this_package(conf=BeartypeConf(hint_overrides=FrozenDict({
list[str]: list[str] | tuple[str, ...]}))) # <-- pretend this makes sense
Frozen dictionaries! It's happening, because beartype.FrozenDict is making it happen:
from beartype import FrozenDict
# Finally, a set of frozen dictionaries! Yes, it's all true. Now you too can use
# dictionaries as dictionaries keys or set members. Why? Because you can.
freezing_my_dict_off = {
FrozenDict({'My ganglia!': 'It hurts.'}),
FrozenDict({'What even is a ganglia?': 'No idea. But it surely hurts.'}),
}
Probably other stuff! But nobody cares, because nobody even read this far. WAIT. You're reading this far. Clearly, you're somebody – somebody awesome who actually has hair and is profoundly changing the world! It only goes to show you can't believe anything you read in a changelog anymore. 2025: "So even the changelogs lie now, huh?"
<sup>@beartype 0.21.0rc0: If you don't feel like a wild animal while coding, can it be called coding?</sup>
@beartype 0.21.0rc0 now officially supports all possible forms of recursion in type hints. This includes directly recursive PEP 695 type aliases, indirectly recursive PEP 484 generics, and @beartype-specific hint overrides. Which you prefer depends on which bitter pill you're willing to swallow:
If you're willing to require Python ≥ 3.12 as a mandatory dependency, prefer PEP 695 type aliases. They're concise. They're descriptive. They're elegant. They "just work" intuitively in the exact way you expect them to:
# Annotate recursive data structures with a "simple" one-liner. \o/
type RecursiveListExplodesYourApp = list[RecursiveListExplodesYourApp]
If you're unwilling to require Python ≥ 3.12 as a mandatory dependency, fallback to PEP 484 self-subscripted generics. They're unconcise. They're non-descriptive. They're inelegant. They require heavy lifting on your part before they start working. But they do work under Python ≥ 3.9, which is more than we can say for PEP 695:
# One line that makes sense (above) or five lines that don't make sense (below)?
# Let the cat decide. ¯\_(ツ)_/¯
from typing import TypeVar
T = TypeVar('T')
class GenericList(list[T]):
pass
GenericRecursiveListExplodesYourApp = GenericList[GenericList]
Let's take this one recursive app destroyer at a time.
<sup>@beartype 0.21.0rc0: this is the biggest animated gif i have ever seen</sup>
Directly recursive PEP 695 type aliases is what everybody who wants recursive type hints wants. Against all odds, you're actually reading this. You want recursive type hints. Thus, you want:
# Type hint matching an infinitely recursive list. Look, I don't know. This is for
# the extreme sports coders that like to live dangerously and code even harder.
type RecursiveListExplodesYourApp = list[RecursiveListExplodesYourApp]
# @beartype now type-checks this infinitely recursive list in O(1) time. Of
# course, that's impossible. But @beartype doesn't even care anymore! F- it!
from beartype import beartype
@beartype
def dangerous_func_means_well(oh_gods: RecursiveListExplodesYourApp) -> None:
'''
Dangerous function iteratively recurses into the passed infinitely recursive
list until either bottoming out at the same list... *or blowing up.*
Which do you hope happens first?
'''
# The growing terror you feel just speed-reading this code is real.
seen_horror_ids: set[int] = set()
unseen_horrors: list[RecursiveListExplodesYourApp] = list((oh_gods,))
# Recurse into that terror. Recurse until your face is numb, like mine.
while unseen_horrors:
# Pop that terror like a meat balloon. If it squishes, you must pop it.
seen_horror = unseen_horrors.pop()
print(f'Visiting infinitely recursive list: {id(seen_horror)}')
# Awaken from this logic nightmare, gentle reader!
if id(seen_horror) in seen_horror_ids:
print("Recursion detected! We're outta here, suckers!")
break
# Pretend this does what the docstring says this does. *gulp*
seen_horror_ids.add(id(seen_horror))
unseen_horrors.append(seen_horror[0])
# Infinitely recursive list. If you try this in the office, you may regret the
# fateful day your career decisions plummeted down a cliff.
OH_GODS = []
OH_GODS.append(OH_GODS)
# Pass this function valid input. Stare down the infinitely recursive list?
# Don't mind if I do! Gape in awe before infinity blows up your call stack.
dangerous_func_means_well(OH_GODS)
# Pass this function invalid input. No! No! Gods! NOOOOOOOOOOOOOOOOOOOOOOO!
dangerous_func_means_well(['Open-source', 'sells,' 'but', "who's", 'buying?'])
...which raises the expected output and exception traceback:
Visiting infinitely recursive list: 133179499204736
Visiting infinitely recursive list: 133179499204736
Recursion detected! We're outta here, suckers!
Traceback (most recent call last):
File "/home/leycec/tmp/mopy.py", line 48, in <module>
dangerous_func_means_well(['Open-source', 'sells,' 'but', "who's", 'buying?'])
~~~~~~~~~~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "<@beartype(__main__.dangerous_func_means_well) at 0x792044b9c360>", line 40,
in dangerous_func_means_well
beartype.roar.BeartypeCallHintParamViolation: Function __main__.dangerous_func_means_well() parameter oh_gods=['Open-source', 'sells,but',
"who's", 'buying?'] violates type hint RecursiveListExplodesYourApp, as list index 2
item str "who's" not instance of list.
Pore one out for the unsuspecting @beartype users that actually tried to run the above example. Their smoking CPUs are no longer with us. What remains of the ruin of their motherboards is now locked into a segfaulting bootloop featuring a cackling ASCII-art bear. It is sad.
<sup>@beartype 0.21.0rc0: "zomg so cuuuuuute oh my brain hurts nooooooooooooooo"</sup>
What? Catch? Surely you jest! There's no... oh, who am I kidding. There are huge catches associated with PEP 695. For one, @beartype intentionally does not support older PEP-noncompliant variants of recursive type hints that used stringified forward references. You might occasionally see crufty stuff like this floating around StackOverflow, older codebases, or the mypy issue tracker:
HorrifyingRecursiveTypeHint = Union[str, 'HorrifyingRecursiveTypeHint']
@beartype doesn't support that. Using stringified forward references to induce recursion is non-standard. @beartype probably could support that, but there's not much point in supporting non-standards when standardized alternatives exist. That's why...
@beartype 0.21.0rc0 only supports PEP 695: the only standard for defining recursive type hints. Everything else was just something mypy made up. Recursive type aliases now work wonderfully under Python ≥ 3.12 – but that's the gotcha here.
<sup>@beartype 0.21.0rc0: rambo with a sword is something that happened only on an alternate timeline... but it still happened</sup>
That's right. You love to hate it. PEP 695 is unusable under Python ≤ 3.11. Attempting to define any type alias under Python ≤ 3.11 results in CPython raising an unreadable "SyntaxError: invalid syntax" exception.
In a year or two, this will be significantly less of a hard blocker for everyone. Increasingly, nobody cares about Python ≤ 3.11. Do you care about Python ≤ 3.11? Maybe – but you probably shouldn't, unless your huge userbase is obsessed by Python ≤ 3.11. In that case, you're kinda screwed. You have to choose between your love for recursion and your love for having users. Tough choice. I'd choose recursion, personally.
<sup>beartype 0.21.rc0: users who hate recursion are users who make your face contort into a tight rictus of agony</sup>
Absolutely! Totally! How could anything else possibly go wrong!
...oh, who am I kidding!?!?!? There is yet another huge catch associated with PEP 695. @beartype does not deeply type-check recursive data structures to a countably infinite depth of nested recursion. Instead, @beartype:
Let's just accept this is happening. But why is this happening? Coupla reasons, fam:
O(1) time complexity. Deeply type-checking a recursive data structure with recursive height k would necessitate linear-time O(k) time complexity in @beartype – violating @beartype's fundamental efficiency guarantee.bad_list = []; bad_list.append(bad_list)). Of course, an iterative approach could be protected against these edge cases by dynamically generating type-checking code that maintains:
type alias to be type-checked, one set of the IDs of all previously type-checked objects. But now @beartype would need to allocate and append to one friggin' set for each recursive type alias for each function call. Space and time efficiency rapidly spirals into the gutter and then clutches its aching head like in a depressing Leaving Only Python ≥ 3.12!? Only one layer of recursion!?
<sup>@beartype 0.21.0rc0: let's get sweaty, together</sup>
Let's assume you hate requiring Python ≥ 3.12. You still love Python 3.9, even though nobody else does. You walk your own dark road. In this case, you want...
Self-subscripting generics, huh? You may now be thinking:
"But what does that even mean? How can a generic subscript itself? What even are generics? What does "subscription" mean? What does anything mean in a post-modern world of fluid subjectivity?"
Continue reading as you walk your own dark road.
Two months ago, ostensible typing genius @EtaoinWu (Yue Wu) invented indirectly recursive type hints at #510. It probably wasn't even an accident. @EtaoinWu probably did it on purpose. Some people are like that. They just like smashing things with their brain hammers until something finally gives. This is that thing.
In the darkness of my man-lair, I realized that @EtaoinWu's approach can be generalized to create indirectly recursive type hints under Python ≤ 3.11. Since Python ≤ 3.11 fails to support PEP 695 recursive type aliases, it was previously believed that recursive type hints could only be "officially" created under Python ≥ 3.12.
Not so. By abusing PEP 484 or PEP 585 generics, you can actually create recursive type hints under Python ≤ 3.11. These hints are fully PEP-compliant. They're valid. They satisfy typing standards. Much like me, however, they're also super weird. You'll frown at them when you see them awkwardly shuffling past you on the sidewalk. You'll also have no choice but to use them if you want to type recursive data structures under Python ≤ 3.11.
To induce recursion without directly defining a PEP 695-compliant recursive type alias, "simply":
Behold! This is indirect recursion via self-subscripting generics:
CAUTION: Merely reading this code abomination could cause your sanity to slip even further into the yawning abyss off the coast of California known only as R'lyeh.
# Import boring stuff you've long grown to loathe. Kinda sad, actually.
# Shouldn't boilerplate like this spark joy instead? I agree.
from beartype import beartype
from typing import TypeVar
# Define a normal unbound type variable. Enjoy it. This is the last normal
# one-liner you will ever see.
T = TypeVar('T')
# Define a normal PEP 585-compliant generic parametrized by that variable. Still
# normal. Still sane. Feels good. Yet, that feeling of unspeakable horror...
class GenericList(list[T]):
pass
# Define a type hint subscripting that generic... *BY ITSELF!?*
#
# Indeed. This type hint, for example, matches an infinitely recursive list
# (i.e., a list such that all items of this list are also infinitely recursive
# lists of the same type).
IndirectlyRecursiveList = GenericList[GenericList]
@beartype
def destroy_the_universe(with_danger_list: IndirectlyRecursiveList) -> None:
'''
Prove that @beartype will let you destroy the universe, if only your
intentions are pure.
'''
print(with_danger_list)
# Define an infinitely recursive non-empty list satisfying this type hint.
super_danger_list = IndirectlyRecursiveList()
super_danger_list.append(super_danger_list)
# Prove that @beartype accepts your risky life choices.
destroy_the_universe(super_danger_list)
# Define a boring non-recursive non-empty list violating this type hint.
super_boring_list = IndirectlyRecursiveList([
'Super', 'boring', 'list', 'hates', 'fun.'])
# Prove that @beartype rejects your safe life choices.
destroy_the_universe(super_boring_list)
...which prints the expected output and exception traceback:
[[...]]
Traceback (most recent call last):
File "/home/leycec/tmp/mopy.py", line 45, in <module>
destroy_the_universe(super_boring_list)
~~~~~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^
File "<@beartype(__main__.destroy_the_universe) at 0x775b159d1440>", line 53, in destroy_the_universe
beartype.roar.BeartypeCallHintParamViolation: Function
__main__.destroy_the_universe() parameter
with_danger_list=['Super', 'boring', 'list', 'hates', 'fun.'] violates type hint
__main__.GenericList[__main__.GenericList], as generic superclass list[~T] of
<class "__main__.GenericList"> index 3 item str 'hates' not instance of
<class "__main__.GenericList">.
WOAH. The official repr() string for an infinitely recursive list generic is [[...]]. CPython just did that. We didn't do anything to make CPython do that. Somehow, that discovery is the coolest part of this whole changelog. I feel sad. :sob:
Voila! You've just created a recursive type hint that works under literally all Python versions – including Python ≤ 3.11. Nobody intended for anyone to do this. Thanks to the sickening force of the human mind, you can now do this.
Kinda surprised that nobody ever thought to subscript a generic by itself. Or did they!? Yeah... they probably did. But no @beartype users ever did that or somebody would have pounded their fists on our issue tracker about that. Or would they!? Yeah... they probably would. 😅 💦
<sup>@beartype 0.21.0rc0: these tears i shed for your code are manly</sup>
No idea. I care in the abstract sense of the word "care." Computer science is a super-fun literary puzzle with real-world implications – which makes it even funner than "normal" puzzles, which are still fun but don't touch the real world in any meaningful way. The lolz. That's what I'm saying. I did this for the lolz.
If you're reading this from the comfort of your PodBed™ in the Year 2075, please know that I did everything I could to make your life better. I solved puzzles. I meant well. Now, future human (or human-like AI construct), my future is your grim struggle for daily sustenance wondrous present in a utopian dream-world.
May this small piece of the recursive puzzle assist you in your own puzzle-wrangling.
<sup>@beartype 0.21.0rc0: because nobody tells you what to do anymore</sup>
Previously, @beartype hint overrides sorta but not really worked. Now, @beartype hint overrides actually do work for all possible use cases. Of course, I never got around to documenting hint overrides.
But don't let that sensible obstacle that should deter you deter you! Use undocumented APIs. Live a little. Let your dangling docstrings hang all out.
Lie to your userbase (and yourself) by globally replacing type hints without anyone's consent or knowledge. Not sure why anyone would want to behave like this, honestly. Therefore, @beartype allows you to behave like this. We support bad habits and so should you:
# Import tons of weirdo @beartype stuff. Look. I don't know either.
from beartype import beartype, BeartypeConf, FrozenDict
# Define a new @beartype decorator named @riskytype. Unlike @beartype, @riskytpe
# performs dangerous type hint overrides by replacing all "list[str]" type hints
# with "list[str] | tuple[str, ...]". Feels good. Users can now pass tuples of
# strings to all callables annotated as accepting only lists of strings. waaat?
riskytype = beartype(conf=BeartypeConf(hint_overrides=FrozenDict({
list[str]: list[str] | tuple[str, ...]})))
# Define a risky function decorated by @riskytype. *gulp*
@riskytype
def risky_func(risky_arg: list[str]) -> str:
return risky_arg[0]
# Prove that this function walks on the wild side.
print(risky_func(['This is fine.', 'You can tell because of my sweaty hand.']))
print(risky_func(('This is totally sus.', 'Users are panicking already.')))
# Prove that this function still occasionally behaves itself.
print(risky_func({'This is beyond sus...', '...where not even @beartype dares.'}))
...which prints the expected output and exception traceback:
This is fine.
This is totally sus.
Traceback (most recent call last):
File "/home/leycec/tmp/mopy.py", line 23, in <module>
print(risky_func({'This is beyond sus...', '...where not even @beartype dares.'}))
~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "<@beartype(__main__.risky_func) at 0x7370c39ce840>", line 48, in risky_func
beartype.roar.BeartypeCallHintParamViolation: Function __main__.risky_func()
parameter risky_arg={'This is beyond sus...', '...where not even @beartype dares.'}
violates type hint list[str], as set {'This is beyond sus...',
'...where not even @beartype dares.'} not list or tuple.
<sup>@beartype 0.21.0rc0: when you feel the need to suck on a bottle in the darkness as an afro ninja looks on in shock</sup>
In the now-legendary GitHub poll "Tell @leycec What to Do", everybody told @leycec to type-check PEP 557 dataclass fields on assignment. Thus, @beartype 0.21.0rc0 now type-checks dataclasses... sorta.
That's sorta right. Sorta means this mostly works, but might not. Type-checking dataclasses is hard. I am soft-bellied and lazy. After combining these adjectives, you get half-hearted dataclass type-checking.
@beartype only conditionally type-checks dataclass fields when you explicitly tell @beartype to type-check dataclass fields by enabling our newly introduced BeartypeConf(is_pep557_fields: bool = False) configuration option. For safety, this option is disabled by default. Ever since @beartype accidentally blew up PyTorch, your safety is our paramount concern. I can't have Microsoft breathing down my neckbeard again. Please! Not that...
When you want dataclass type-checking, you have to enable dataclass type-checking – like so:
# Import so many things you can barely see what matters anymore.
from beartype import beartype, BeartypeConf
from dataclasses import dataclass, InitVar
from typing import ClassVar
@beartype(conf=BeartypeConf(is_pep557_fields=True)) # <-- check it like a bear boss
@dataclass
class MuhDataclass(object):
muh_int: int
muh_classvar: ClassVar[str] = 'This is fine. Srsly. Does @leycec not have Buddha nature?'
muh_initvar: InitVar[bytes] = b'This is fine, too. No joke. No shade. No idea.'
# *GOOD.*
good_data = MuhDataclass(muh_int=42) # <-- this works
good_data.muh_int = 0xCAFEBABE # <------- this works, too
# *BAD.*
bad_data = MuhDataclass(muh_int=42) # <-- still works
bad_data.muh_int = '0xCAFEBABE' # <------ this fails! *YAY*!
...which raises the expected type-checking violation:
beartype.roar.BeartypeDecorHintParamDefaultViolation: Dataclass MuhDataclass(muh_int=42)
attribute 'muh_int' new value '0xCAFEBABE' violates type hint <class 'int'>,
as str '0xCAFEBABE' not instance of int.
As the above example demonstrates, this preliminary functionality supports cafe babes. Uhh... I mean, this supports:
@dataclass decorator passed no keyword parameters. :+1:@dataclass(frozen=True). :hand_with_index_finger_and_thumb_crossed:@dataclass(slots=True). :money_mouth_face:Truly, now you too can get Poor Man's Pydantic<sup>©</sup> for free from the comfort of your own AI-assisted keyboard while doing even less work than you ordinarily would while nursing a video game hangover on Sunday morning. @leycec did all the work for you and painfully regretted deeply cherished this character- and morale-building life lesson.
<sup>who did this to you, @beartype!?! oh, it was just dataclasses.</sup>
Thanks to the non-triviality of dataclasses and my own moral failings (read: "I am laziness incarnate"), this functionality currently fails to support all possible dataclass configurations and use cases. Popular edge cases not supported include:
Dataclass subclasses (i.e., dataclasses subclassing other dataclasses). This is completely untested. No idea what happens. Could blow up everything. Could do nothing, which is better than just blowing up everything.
PEP 563 (i.e., from __future__ import annotations), which almost certainly raises exceptions when enabling is_pep557_fields=True.
Dataclass fields annotated by one or more relative forward references (i.e., strings referring to the names of currently undefined types, subsequently defined in the current submodule), which almost certainly raises exceptions when enabling is_pep557_fields=True: e.g.,
from dataclasses import dataclass
@dataclass
class UnsupportedDataclass(object):
unsupported_field: 'UndefinedType' # <-- BREAKS EVERYTHING, YO
class UndefinedType(object): pass
Until @beartype fully supports all of the above edge cases, is_pep557_field will continue defaulting to False. Someday, this will surely work for everybody. Until then, let us collectively sob. 😭
<sup>@beartype 0.21.0rc0: teach a dev to crush bugs for a day and he'll crush bugs for a life</sup>
Python needs an official frozendict implementation, if only to shut down continual demands for an official frozendict implementation. Thankfully, you use @beartype.
@beartype 0.21.0rc0 now offers a public frozen dictionary type for you: beartype.FrozenDict! It actually works! It's mostly still C-based and thus fast! We tested everything and then some! We stuffed everything inside these things and they still pretended to work! We use frozen dictionaries everywhere in the @beartype codebase! Now, so can you!
beartype.FrozenDict: because Hell will freeze over before Python ever gets an official frozendict implementation.
from beartype import FrozenDict
# Finally, a set of frozen dictionaries! Yes, it's all true. Now you too can use
# dictionaries as dictionaries keys or set members. Why? Because you can.
freezing_my_dict_off = {
FrozenDict({'My ganglia!': 'It hurts.'}),
FrozenDict({'What even is a ganglia?': 'No idea. But it surely hurts.'}),
}
<sup>@beartype 0.21.0rc0: we heard you wanted some FrozenDict with your FrozenDict</sup>
...to financially feed @leycec and his friendly @beartype through our ancient GitHub Sponsors profile that predates the existence of dinosaur-like AI chatbots. Come for the candid insider photos of a sordid and disreputable life in the Canadian interior; stay for the GitHub badge and warm feelings of general goodwill.
Cue hypnagogic rave music that encourages fiscal irresponsibility. :musical_note: :musical_keyboard: :notes:
@beartype high-fives the reclusive secret society of worldwide bear bros who might possibly care about this. You are the select few. The elect enlightened. You are:
@posita, @wesselb, @tusharsadhwani, @JWCS, @patrick-kidger, @EtaoinWu, @iamrecursion, @Moosems, @langfield, @sylvorg, @mzealey, @thetianshuhuang, @RomainBrault, @ddorian, @rg936672, @alisaifee, @ArneBachmannDLR.
The burden of QA is high – but you have chosen to carry the smelly torch. Keep that suspiciously purple flame alive! The recursive data structure you crush the bugs out of tonight may very well be your own.
<sup>@beartype 0.21.0rc0 stands poetically before the burning wreckage of your competitor's codebase</sup>
@beartype 0.20.2 teleports seemingly from out of nowhere into the former safety of your Ungendered Person Cave™, where not even smelly bears that eat
@beartype 0.20.2 teleports seemingly from out of nowhere into the former safety of your Ungendered Person Cave™, where not even smelly bears that eat all your bugs are welcome:
pip install --upgrade beartype
@beartype 0.20.2 apologizes for the bald-faced transgressions of @beartype 0.20.1, which tried to resolve issue #512 for @rg936672 but mostly did nothing except sit around and read fantasy books. @beartype 0.20.2 would prefer it if @beartype 0.20.1 were never spoken of again. "What @beartype 0.20.1?", am I right?
@beartype 0.20.2 and your moral compass knows I'm right. Which is why...
@beartype 0.20.2 is brought to you by...
This release comes courtesy these proud GitHub Sponsors, without whom @leycec's cats would currently be eating grasshoppers:
Thanks so much, masters of fintech and metrology.
<sup>The Masters of Fintech and Metrology. That's who.</sup>
It's better you not know about issues #512 or #514. In the land of the blind bug-crusher, ignorance is bliss and the one-eyed @beartype is king. By the overwhelming power of ignorance, no problems never existed. "What problems?", am I right?
Wait. Does "no problems never existed" actually mean "some problems always existed"? Double negatives destroy yet another convincing one-liner. Thanks fer nuffin', incomprehensible English language!
...to financially feed @leycec and his friendly @beartype through our ancient GitHub Sponsors profile that predates the existence of dinosaur-like AI chatbots. Come for the candid insider photos of a sordid and disreputable life in the Canadian interior; stay for the GitHub badge and warm feelings of general goodwill.
Cue hypnagogic rave music that encourages fiscal irresponsibility. :musical_note: :musical_keyboard: :notes:
Bear Club welcomes long-standing user @rg936672 to bathe in the lukewarm ambiance wafting off @beartype 0.20.2. It feels good. Therefore, it is good.
@beartype 0.20.1 materializes before your astonished keyboard with an explosive fizzy sizzling not unlike that of a flimsy soda can bursting its alumi
@beartype 0.20.1 materializes before your astonished keyboard with an explosive fizzy sizzling not unlike that of a flimsy soda can bursting its aluminum seams all over your astonished keyboard:
pip install --upgrade beartype
Because I am a bald middle-aged man, I still use pip. Someday I will update my priors and switch to uv. Someday... but not today. :face_holding_back_tears:
@beartype 0.20.1 brings a ton of fun stuff! It almost made the cut for a full-fledged minor @beartype 0.21.0 release. In the end, I couldn't bear the thought of another never-ending release candidate cycle. And neither could you. Which is why...
<sup>@beartype 0.20.1 is the shark in this metaphor. pretty sure that makes you the diver.</sup>
@beartype 0.20.1 is brought to you by...
This release comes courtesy these proud GitHub Sponsors, without whom @leycec's cats would currently be eating grasshoppers:
Thanks so much, masters of fintech and metrology.
<sup>The Masters of Fintech and Metrology. That's who.</sup>
Let's start with the good stuff.
In the now-legendary GitHub poll "Tell @leycec What to Do", everybody told @leycec to type-check dataclasses. Thus, @beartype 0.20.1 now type-checks dataclasses... sorta.
Type-checking dataclasses is hard. I am soft-bellied and lazy. After combining these things, you get half-hearted dataclass type-checking. @beartype only conditionally type-checks dataclasses when you explicitly tell @beartype to type-check dataclasses by enabling our newly introduced BeartypeConf(is_check_pep557: bool = False) configuration option. For safety, this option is disabled by default.
When you want dataclass type-checking, you have to enable dataclass type-checking – like so:
from beartype import beartype, BeartypeConf
from dataclasses import dataclass, InitVar
from typing import ClassVar
@beartype(conf=BeartypeConf(is_check_pep557=True)) # <-- check it like a boss
@dataclass
class MuhDataclass(object):
muh_int: int
muh_classvar: ClassVar[str] = 'This is fine. Srsly. Does @leycec not have Buddha nature?'
muh_initvar: InitVar[bytes] = b'This is fine, too. No joke. No shade. No idea.'
# *GOOD.*
good_data = MuhDataclass(muh_int=42) # <-- this works
good_data.muh_int = 0xCAFEBABE # <------- this works, too
# *BAD.*
bad_data = MuhDataclass(muh_int=42) # <-- still works
bad_data.muh_int = '0xCAFEBABE' # <------ this fails! *YAY*!
...which raises the expected type-checking violation:
beartype.roar.BeartypeDecorHintParamDefaultViolation: Dataclass MuhDataclass(muh_int=42)
attribute 'muh_int' new value '0xCAFEBABE' value '0xCAFEBABE' violates type hint <class 'int'>,
as str '0xCAFEBABE' not instance of int.
As the above example demonstrates, this preliminary functionality supports standard dataclass fields annotated by either:
typing.ClassVar[...] type hints. 🥰dataclasses.InitVar[...] type hints. 😸<sup>who did this to you, @beartype!?! oh, it was just dataclasses.</sup>
Thanks to the non-triviality of dataclasses and my own moral failings (read: "I am laziness incarnate"), this functionality currently fails to support all possible dataclass configurations and use cases. Popular edge cases not supported include:
Frozen dataclasses (e.g., @dataclass(frozen=True)), which are currently guaranteed to raise exceptions when enabling is_check_pep557=True.
Slotted dataclasses (e.g., @dataclass(slots=True)), which are currently guaranteed to raise exceptions when enabling is_check_pep557=True.
Dataclass subclasses (i.e., dataclasses subclassing other dataclasses). This is completely untested. No idea what happens. Could blow up everything. Could do nothing, which is better than just blowing up everything.
PEP 563 (i.e., from __future__ import annotations), which almost certainly raises exceptions when enabling is_check_pep557=True.
Dataclass fields annotated by one or more relative forward references (i.e., strings referring to the names of currently undefined types, subsequently defined in the current submodule), which almost certainly raises exceptions when enabling is_check_pep557=True: e.g.,
from dataclasses import dataclass
@dataclass
class UnsupportedDataclass(object):
unsupported_field: 'UndefinedType' # <-- BREAKS EVERYTHING, YO
class UndefinedType(object): pass
Until @beartype fully supports all of the above edge cases, is_check_pep557 will continue defaulting to False. Someday, this will surely work for everybody. Until then, let us collectively sob. 😭
<sup>teach a dev to crush bugs for a day and he'll crush bugs for a life</sup>
Previously, @beartype only supported the core Click project for generating Pythonic CLIs and TUIs. Now, @beartype 0.20.1 extensibly supports the full Click ecosystem of Click-based projects – including the new BigBoy™, rich-click. Combine the venerable powers of Click + Rich. Truly, your app will own the terminal:
from beartype import beartype
from rich_click import command
@beartype # <-- actually works now. i know. i'm stunned, too.
@command()
def do_something_for_leycecs_sake() -> int:
return 0xFEEDFACE # Feed that face! Feed it good.
<sup>your silky smooth Rich TUI has never felt so good</sup>
That's it, folks! That's all we've got. It wasn't much, but it was still more than you wanted on a Friday morning. This has been @beartype 0.20.1. Thanks so much for having us. If anyone needs us, we'll be playing video games and listening to Finnish viking metal all night. :metal:
...to financially feed @leycec and his friendly @beartype through our ancient GitHub Sponsors profile that predates the existence of dinosaur-like AI chatbots. Come for the candid insider photos of a sordid and disreputable life in the Canadian interior; stay for the GitHub badge and warm feelings of general goodwill.
Cue hypnagogic rave music that encourages fiscal irresponsibility. :musical_note: :musical_keyboard: :notes:
Bear Club welcomes long-standing users @RomainBrault, @rg936672, and @GithubCamouflaged to bask in the code-warming radiance that is @beartype 0.20.1.
<sup>don't by shy! come on in. the water's warm. there's more than enough QA to go around...</sup>
…LEGO Millennium Falcon constructed entirely from deprecated type hints. Now, it's dead. Only my baldness remains. Python makin' me feel old over here.
Beartype 0.20.0 catapults out of your CRT monitor from the 90's that contains only four pounds of lead, across your mechanical keyboard with the clacky keys and vibrant crumb trails, and into your lap. Startled, you shriek in fear. Then astonishment. Then back to fear. Trembling, your fingers reach for...
pip install --upgrade beartype # <-- bugger the bugs
Caveat Emptor: What follows is a lazy copy-paste of our prior changelog for Beartype 0.20.0 Release Candidate 0. Therefore, this is already boring the snot out of you. That's a good thing. Laziness is the root of all QA stability.
@beartype 0.20.0 gurgles contentedly as you wipe the birthing fluids from its forehead. You choke back tears. In a moment of madness that borders on the divine, you pull the trigger. You update. You're in too deep now. The sunk cost fallacy you feel is real. Your devbox shudders. Your mechanical keyboard spills sugary soda all over itself. Your RSI-wracked mouse hand pulsates with the pre-install jitters. Surely the second coming of QA is at hand.
<sup>@beartype 0.20.0: and you thought Gymnastics Turtle was weird</sup>
@beartype 0.20.0 is brought to you by...
This release comes courtesy these proud GitHub Sponsors, without whom @leycec's cats would currently be eating grasshoppers:
Thanks so much, masters of fintech and metrology.
<sup>The Masters of Fintech and Metrology. That's who.</sup>
And now for something fishy.
Absolutely! Well, surely. Well, probably. Well, possibly. Well, maybe.
@beartype 0.20.0 brings to bear a whole new lineup of QA goodies. You never knew you needed these QA goodies until a small voice inside of you whispered:
"You do."
Before we get to some actual meaningful content in this changelog, though...
<sup>Blast Hardcheese isn't to blame for @beartype 0.20.0's litany of questionable new "features"... but your coworker might be</sup>
Left to my own devices, I just play video games and obsessively rummage around in the bike shed with PEP standards nobody cares about. This is why...
I implore you to vote in this GitHub forum poll. Yes. It's all true. User opinions always mattered, but now user opinions really matter. I can't pretend they don't exist anymore. For the first time ever, you can force me to do your questionable and unsavoury bidding. Tell me what to do this summer. Vote now. Vote often. Vote hard. But for the sake of the bugs crushing your workload, vote. :full_moon_with_face:
<sup>a vote for bob evil is a vote for @beartype 0.21.0</sup>
Iterable[...] + Container[...] = BBFFLs (Best Bear Friends for Life)@beartype now deeply type-checks the last remaining PEP 484- and 585-compliant container type hints in O(1) constant time, including:
collections.abc.Container[...] type hints.collections.abc.Iterable[...] type hints.collections.abc.Reversible[...] type hints.typing.Container[...] type hints.typing.Iterable[...] type hints.typing.Reversible[...] type hints.@beartype now type-checks exactly one item of containers annotated with general-purpose container type hints like Iterable[...] and Container[...] in O(1) constant time. How? Smarty bear pants. @beartype intelligently detects whether a container is:
list[str]), in which case a pseudorandom item of that
sequence is type-checked.set[int]), in which case only the first item of that
collection is type-checked.‼ Plum users may now dispatch on all of the above.
collections.abc.Iterable[...]is the Big One™, of course. This is the profit of depending on @beartype. You wait years for @leycec to do something. Finally, @leycec does a thing. Your code works. Users cheer. It is delicious.
<sup>beartype 0.20.0 isn't laughing. beartype 0.20.0 doesn't even know what's happening anymore...</sup>
@beartype now deeply type-checks PEP 484-compliant type variables (e.g., T = typing.TypeVar('T')) for a variety of common use cases. Mostly, this means type variables whose type-checking can be entirely decided at decoration time by the @beartype decorator.
Since deciding type-checking at decoration time is really fast, deeply type-checking type variables in these use cases is really fast as well. Like, O(1) fast. Like everything @beartype does, these type variables are cost-free. They don't cost anything, so you'd might as well use them. This probably marks the first serious attempt by any package to tackle type variables at runtime.
This support fully covers these common use cases:
MuhList[int] given the type class MuhList[T](list[T]): ...).MuhAlias[int] given the type alias type MuhAlias[T] = list[T] | T | int).Let's take a swan dive into the deep end of...
@beartype now propagates child hints up generic type hierarchies. Because @beartype values the cooperation of coworkers you barely convinced to use @beartype in the first place, @beartype propagates child hints efficiently, recursively, and (most importantly) safely. No generics are harmed in the propagation of child hints.
The proof is in the syntactically highlighted rainbow pudding. In this example, we bring the swift fist of justice to Python QA. First, we define a generic parametrized by a type variable T. Next, we annotate a function with a type hint created by subscripting that generic with the child hint int. Finally, @beartype does the rest by propagating that child hint int into that type variable T up the type hierarchy of that generic.
Behold! Boredom personified, yet you can't turn your lidded eyes away:
from beartype import beartype
from collections.abc import Container, Iterable, Iterator, Sequence
# Define a PEP 585-compliant generic satisfying both the
# "collections.abc.Iterable" and "Container" abstract base classes (ABCs). W00t!
@beartype
class SoDumbSoDelicious[T](Iterable[T], Container[T]):
def __init__(self, sequence: Sequence[T]) -> None:
self._sequence = sequence
def __contains__(self, obj: object) -> bool:
return obj in self._sequence
def __iter__(self) -> Iterator[T]:
return iter(self._sequence)
def __len__(self) -> int:
return len(self._sequence)
# Define a function accepting an instance of this generic constrained to contain
# *ONLY* integers. Yuppers. It's true. @beartype actually type-checks this now.
@beartype
def tastes_like_lard(yum: SoDumbSoDelicious[int]) -> int:
return next(iter(yum))
# Define delectable instances of this generic. Prove this isn't just crazy-talk!
love_me_some_lard = SoDumbSoDelicious((0xCAFE, 0xBABE))
gods_no_more_lard = SoDumbSoDelicious(('Cafe', 'Babe!'))
# Assert that calling this function with a valid parameter returns the
# expected value. You are the cafe. You are the lard. You knew you shouldn't
# have read that, but you kept on doing it. The punchline so wasn't worth it.
assert tastes_like_lard(love_me_some_lard) == 0xCAFE # <-- oh not that cafe
# Call this function with an invalid parameter, which then raises a
# type-checking violation. May the Gods strike me down if lard is bad for you!
tastes_like_lard(gods_no_more_lard) # <-- ...you will eat lard and like it
...which raises the expected type-checking violation:
Traceback (most recent call last):
File "/home/leycec/tmp/mopy.py", line 35, in <module>
tastes_like_lard(gods_no_more_lard) # <-- ...you will eat lard and like it
~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^
File "<@beartype(__main__.tastes_like_lard) at 0x7fce8b0828e0>", line 89, in tastes_like_lard
beartype.roar.BeartypeCallHintParamViolation: Function
__main__.tastes_like_lard() parameter yum=<__main__.SoDumbSoDelicious object at
0x7fce8b35d6d0> violates type hint __main__.SoDumbSoDelicious[int], as generic
superclass collections.abc.Iterable[T] of <class "__main__.SoDumbSoDelicious">
index 0 item str 'Cafe' not instance of int.
In other words, @beartype now "knows" that any object typed as SoDumbSoDelicious[int] should be an iterable container whose items are all integers. Under the furry hood, @beartype "knows" this by recursively replacing each instance of the type variable T with the child hint int within the generic type hierarchy of SoDumbSoDelicious .
In other words, @beartype now correctly propagates mappings from type variables parametrizing generic declarations (e.g., the T in class SoDumbSoDelicious[T](Iterable[T], Container[T]):) to the child hints subscripting usage of those generics (e.g., the int in SoDumbSoDelicious[int]). @beartype does this recursively for arbitrarily complex generic type hierarchies.
This broke my brain and took two full months of mostly unpaid volunteerism. That's why I still beg for money on GitHub Sponsors like that hobo chugging Duck wine out of a cardboard box on your commute to work every day. Like the hobo, I had fun. Like the hobo, I had the urge to sleep in the gutter. This feature was so hard I had to refactor the entire @beartype codebase to support it – including @beartype's totally-not-fragile dynamic type-checking code generator that I avoid touching at all costs. That's how totally-not-fragile it is. It's the sort of poorly documented 10,074-line code dump you see prefixed with stultifying ASCII art banners like:
######### LUCK DRAGON EATS YOUR LUNCH, THEN HICCUPS?!? #########
# Here thar be dragons, code matey. Arr. *hiccup* #
# ⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⣀⣀⣤⣤⣤⣤⡼⠀⢀⡀⣀⢱⡄⡀⠀⠀⠀⢲⣤⣤⣤⣤⣀⣀⡀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀ #
# ⠀⠀⠀⠀⠀⠀⠀⠀⠀⣠⣴⣾⣿⣿⣿⣿⣿⡿⠛⠋⠁⣤⣿⣿⣿⣧⣷⠀⠀⠘⠉⠛⢻⣷⣿⣽⣿⣿⣷⣦⣄⡀⠀⠀⠀⠀⠀⠀⠀⠀ #
# ⠀⠀⠀⠀⠀⠀⢀⣴⣞⣽⣿⣿⣿⣿⣿⣿⣿⠁⠀⠀⠠⣿⣿⡟⢻⣿⣿⣇⠀⠀⠀⠀⠀⣿⣿⣿⣿⣿⣿⣿⣿⣟⢦⡀⠀⠀⠀⠀⠀⠀ #
# ⠀⠀⠀⠀⠀⣠⣿⡾⣿⣿⣿⣿⣿⠿⣻⣿⣿⡀⠀⠀⠀⢻⣿⣷⡀⠻⣧⣿⠆⠀⠀⠀⠀⣿⣿⣿⡻⣿⣿⣿⣿⣿⠿⣽⣦⡀⠀⠀⠀⠀ #
# ⠀⠀⠀⠀⣼⠟⣩⣾⣿⣿⣿⢟⣵⣾⣿⣿⣿⣧⠀⠀⠀⠈⠿⣿⣿⣷⣈⠁⠀⠀⠀⠀⣰⣿⣿⣿⣿⣮⣟⢯⣿⣿⣷⣬⡻⣷⡄⠀⠀⠀ #
# ⠀⠀⢀⡜⣡⣾⣿⢿⣿⣿⣿⣿⣿⢟⣵⣿⣿⣿⣷⣄⠀⣰⣿⣿⣿⣿⣿⣷⣄⠀⢀⣼⣿⣿⣿⣷⡹⣿⣿⣿⣿⣿⣿⢿⣿⣮⡳⡄⠀⠀ #
# ⠀⢠⢟⣿⡿⠋⣠⣾⢿⣿⣿⠟⢃⣾⢟⣿⢿⣿⣿⣿⣾⡿⠟⠻⣿⣻⣿⣏⠻⣿⣾⣿⣿⣿⣿⡛⣿⡌⠻⣿⣿⡿⣿⣦⡙⢿⣿⡝⣆⠀ #
# ⠀⢯⣿⠏⣠⠞⠋⠀⣠⡿⠋⢀⣿⠁⢸⡏⣿⠿⣿⣿⠃⢠⣴⣾⣿⣿⣿⡟⠀⠘⢹⣿⠟⣿⣾⣷⠈⣿⡄⠘⢿⣦⠀⠈⠻⣆⠙⣿⣜⠆ #
# ⢀⣿⠃⡴⠃⢀⡠⠞⠋⠀⠀⠼⠋⠀⠸⡇⠻⠀⠈⠃⠀⣧⢋⣼⣿⣿⣿⣷⣆⠀⠈⠁⠀⠟⠁⡟⠀⠈⠻⠀⠀⠉⠳⢦⡀⠈⢣⠈⢿⡄ #
# ⣸⠇⢠⣷⠞⠁⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠙⠻⠿⠿⠋⠀⢻⣿⡄⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠈⠙⢾⣆⠈⣷ #
# ⡟⠀⡿⠁⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⣴⣶⣤⡀⢸⣿⠇⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢻⡄⢹ #
# ⡇⠀⠃⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢸⡇⠀⠈⣿⣼⡟⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠈⠃⢸ #
# ⢡⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠈⠻⠶⣶⡟⠋⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⡼ #
# ⠈⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢀⡾⠋⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠁ #
# ⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢸⡁⢠⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀ #
# ⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢀⣿⣿⣼⣀⣠⠂⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀ #
# Dragons ahoy, code matey. Swab the Steam Deck. Arr. #
######### ASCII ART MEANS SWEAT, TEARS, AND CI FAILURE #########
It's likely there are unresolved edge cases I'm blissfully unaware of. If you hit one of these golden landmines, please submit an issue. I'll promptly resolve everything or collapse on my keyboard trying. :cold_sweat:
‼ Plum users may now dispatch on subscripted generics. This is the profit of depending on @beartype. You wait years for @leycec to do something. Finally, @leycec does a thing. Exhaustedly, you pump your hand in the sign of victory. You are vindicated... yet you feel empty.
<sup>awkward life moments (brought to you by @beartype)</sup>
@beartype now propagates child hints up generic type aliases, too. This is genuinely cool. Like, "cool kids" cool. Generic type aliases are kinda like functions or a full-blown templating engine – except for type hints. If you've ever found yourself copy-pasting one stupidly long type hint into another, you've realized you're violating the Don't Repeat Yourself (DRY) principle and are now off the deep end of QA. Thus:
# Instead of copy-pasting hellish type hints surely spawned in the Ninth Circle
# like this...
PygmentsStringToken = list[typing.Union[
tuple[str | collections.abc.Callable[typing.Concatenate[object, object, ...], object], ...],
tuple[str | pygments.token._TokenType[str], ...],
typing.Annotated[collections.abc.Collection[str], beartype.vale.IsInstance[pygments.lexer.include]],
]]
PygmentsBytesToken = list[typing.Union[
tuple[bytes | collections.abc.Callable[typing.Concatenate[object, object, ...], object], ...],
tuple[bytes | pygments.token._TokenType[bytes], ...],
typing.Annotated[collections.abc.Collection[bytes], beartype.vale.IsInstance[pygments.lexer.include]],
]]
# ...just define a single generic type alias like this...
type PygmentsToken[T] = list[typing.Union[
tuple[T | collections.abc.Callable[typing.Concatenate[object, object, ...], object], ...],
tuple[T | pygments.token._TokenType[T], ...],
typing.Annotated[collections.abc.Collection[str], beartype.vale.IsInstance[pygments.lexer.include]],
]]
# ...then subscript that alias with child hints. Look, code metrics! No DRY.
PygmentsStringToken = PygmentsToken[str]
PygmentsBytesToken = PygmentsToken[bytes]
In this example, PygmentsToken may not look like a function – but it pretty much is. It's a "function" that generates a new type hint from a standardized template every time you subscript it with a new child hint.
So what's the catch? We hope you don't mind requiring Python ≥ 3.12 by dropping support for Python ≤ 3.11. Because... that's the catch. If you try to define even a single type alias in a single submodule of your package under Python ≤ 3.11, your entire app unceremoniously blows up with a fatal SyntaxError: invalid syntax exception. Good luck with that.
@beartype 0.20.0: because your users hate Python ≤ 3.11, too.
<sup>barbarian code never got type-checked by @beartype</sup>
I don't even know what "thrumming" is, but I'm pretty sure that's what happens to your sinews when you combine the fearsome power of subscripted generics and subscripted type aliases. The coworker to your right is already cowering. Good. That feeling is good. Soon, they will all kneel! </muhaha— *choking*>
Behold! A subscripted type alias propagating its child hint onto a subscripted generic. Why? Because your QA pipeline wasn't complicated enough and you now need to justify your position to those new bastards in suits nice HR spokespeople:
from beartype import beartype
from collections.abc import Container, Iterable, Iterator, Sequence
# Define the same PEP 585-compliant generic as above. Booooooooring.
@beartype
class SoDumbSoDelicious[T](Iterable[T], Container[T]):
def __init__(self, sequence: Sequence[T]) -> None:
self._sequence = sequence
def __contains__(self, obj: object) -> bool:
return obj in self._sequence
def __iter__(self) -> Iterator[T]:
return iter(self._sequence)
def __len__(self) -> int:
return len(self._sequence)
# Define a PEP 695-compliant type alias unifying this generic with other stuff.
# Look... *I* don't know. You're the genius here. You'll defly get a raise at
# work if you keep pushing out quality code like this.
type MaybeSoDumbSoDelicious[T] = T | MaybeSoDumbSoDelicious[T] | None
# Define a function accepting either an integer, an instance of this generic
# constrained to contain *ONLY* integers, or "None". @beartype type-checks this,
# because @beartype has no say in the matter. @beartype has to do what you say.
# This is why @beartype feels great sadness in the Autumn.
@beartype
def maybe_tastes_like_lard(yum: MaybeSoDumbSoDelicious[int]) -> int:
return next(iter(yum))
# Define delectable instances of this generic. Prove this isn't just crazy-talk!
love_me_some_lard = SoDumbSoDelicious((0x1331, 0xC001))
gods_no_more_lard = SoDumbSoDelicious(('Leet', 'Cool!'))
# Assert that calling this function with a valid parameter returns the
# expected value. You are the cafe. You are the lard. You knew you shouldn't
# have read that, but you kept on doing it. The punchline so wasn't worth it.
assert maybe_tastes_like_lard(love_me_some_lard) == 0x1331 # <-- oh not that cafe
# Call this function with an invalid parameter, which then raises a
# type-checking violation. May the Gods strike me down if lard is bad for you!
maybe_tastes_like_lard(gods_no_more_lard) # <-- ...you will eat lard and like it
...which raises the expected type-checking violation:
Traceback (most recent call last):
File "/home/leycec/tmp/mopy.py", line 42, in <module>
maybe_tastes_like_lard(gods_no_more_lard) # <-- ...you will eat lard and like it
~~~~~~~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^
File "<@beartype(__main__.maybe_tastes_like_lard) at 0x7f89162fa8e0>", line 94, in maybe_tastes_like_lard
beartype.roar.BeartypeCallHintParamViolation: Function
__main__.maybe_tastes_like_lard() parameter yum=<__main__.SoDumbSoDelicious
object at 0x7f89165c5810> violates type hint MaybeSoDumbSoDelicious[int], as
<class "__main__.SoDumbSoDelicious"> <__main__.SoDumbSoDelicious object at
0x7f89165c5810>:
* Not int or <class "builtins.NoneType">.
* Generic superclass collections.abc.Iterable[T] of <class
"__main__.SoDumbSoDelicious"> index 0 item str 'Leet' not instance of int.
...which only goes to show that @beartype now knows everything. Lo! It is known.
<sup>@beartype is getting bad vibes from trumpy</sup>
One ill-fated morning, you realise with a gnawing horror... You've run out of coffee. The Pop-Tarts® box is empty. There's no reason to get up anymore. You greet the watery Sun with a thousand-yard stare half-baked beyond the void of space. Yet, through crusty eyes, you think to yourself:
Can I compare whether one subscripted generic is a subhint of (i.e., both commensurable with and narrower than) another subscripted generic? If I can, why would I want to do that? Is this what life without coffee and Pop-Tarts® is like for billions around the world even today!?!?
I don't know why, but unspecified people <sup>okay, it's @patrick-kidger and @wesselb</sup> want to compare subscripted generics. I smell academia and a burgeoning career built on the shuddering back of @beartype. You might be one of these people or a person like these people. But, let's be honest... you're probably not. You're wondering why you're still reading this and rapidly realizing there's no good answer to that question. Some questions are bad.
Let's pretend you're one of these people. Rejoice! @beartype now decides the least trivial computational puzzle in the field of type systems, because @leycec couldn't bear to see that unresolved [Bug] status for another year:
>>> from beartype.door import is_subhint # <-- it's baaaaaaack
>>> from collections.abc import Sequence
>>> from typing import Generic, TypeVar
# Define some type variables like it's 2017.
>>> S = TypeVar('S')
>>> T = TypeVar('T')
>>> T_sequence = TypeVar('T_sequence', bound=Sequence)
# Define some parametrized generics. Pretend this means something.
>>> class GenericST(Generic[S, T]): pass
>>> class GenericSInt(Pep484GenericST[S, int]): pass
# Decide whether these generics are related or not, especially when subscripted
# by child hints. You don't know why you want to decide this. You just do.
# You've gotta. You're compelled by inner demons to go beyond the pale
# crenellations of normalcy, beyond even the liminal subspaces of QA. WUT?!?
>>> is_subhint(Pep484GenericSInt, Pep484GenericST)
True # <-- ...okay
>>> is_subhint(Pep484GenericSInt, Pep484GenericST[int, int])
False # <-- sure, buddy
>>> is_subhint(Pep484GenericSInt[int], Pep484GenericST)
True # <-- i'm not your buddy, pal
>>> is_subhint(Pep484GenericSInt[int], Pep484GenericST[S, T_sequence])
False # <-- whatever you say, bear boss
>>> is_subhint(Pep484GenericSInt[list], Pep484GenericST[T_sequence, object])
True # <-- pretty sure i no longer know what's happening
>>> is_subhint(Pep484GenericSInt[list], Pep484GenericST[Sequence, Any])
True # <-- seems legit if i squint at it
>>> is_subhint(Pep484GenericSInt[str], Pep484GenericST[T_sequence, S])
True # <-- it's too good to be true
>>> is_subhint(Pep484GenericSInt[Sequence], Pep484GenericST[list, object])
False # <-- finally, a falsehood exposed
>>> is_subhint(Pep484GenericSInt[T_sequence], Pep484GenericST)
True # <-- yeah, right, @beartype! as if
I'm confident you could profitably author multiple doctoral theses strung out across multiple poorly remunerated grad students who hate themselves almost as much as you do by just addressing, redressing, and endlessly rehashing this single issue. Papermill careers are built on the boneless backs of issues like this.
Originally, I wanted to bludgeon everyone in attendance with a tiresome essay doing just that. In the bitter end, even the mere thought of tiring everyone tires me beyond the event horizon of exhaustion.
Still, boredom is its own reward. I'll say that @beartype has probably invented the optimally efficient algorithm for deciding this problem. Nobody cares, of course. Even I am lacklustre about this whole thing.
But a non-recursive depth-first search (DFS) is a glorious self-flagellation that few ever attempt and even fewer survive. This DFS exhibits:
O(1) constant time complexity. Pump that fist!O(jk) quadratic time complexity, where:
j is the largest number of child type hints transitively subscripting an unerased pseudo-superclass of the first generic passed to is_subhint(). You don't even want to know what "unerased pseudo-superclass" means.k is the total number of transitive pseudo-superclasses of the same generic. Ditto.Because the DFS is non-recursive, it's stupidly fast, unreadable, undebuggable, and unmaintainable. This is why we @beartype:
...so that all the suffering is concentrated in one place.
<sup>left: parametrized generics. right: ...is that @leycec?!?</sup>
Of course, @leycec is lazy. @beartype still lacks general-purpose support for type-checking type variables at call time. This means @beartype still ignores type-checking violations involving mismatching types across type variables like:
def muh_func[T](muh_arg: T) -> list[T]:
return ['this is busted', "but you'll never know", 'cause @beartype dumb.']
# Beartype should raise a type-checking violation here, as the list returned by
# this function is a list of strings rather than a list of integers. Sadly,
# beartype currently thinks this is fine and does nothing, much like our cats.
muh_func(0xDEADCODE)
@beartype 0.20.0: shrugging apathetically while your code burns
<sup>the answer may shock you</sup>
@beartype now tolerates these extremely popular third-party packages that hate @beartype ≤ 0.19.0 (and other runtime type-checkers, too):
urllib3.xarray.Yes, these packages hate @beartype (and other runtime type-checkers, too). The irony is especially rich in Pydantic's case, because Pydantic itself is a runtime type-checker. This must be what happens when you go full-Rust.
These packages all doubled down on the typing.TYPE_CHECKING forward reference antipattern, which @beartype 0.21.0 will have a lot to say about. Until then, this is "Leycec's Abbreviated Notes on the Antipattern That Destroys True Goodness and Heroism":
# This is what PEP 484, PEP 563, and @beartype all want you to do. Forward
# referencing external types defined in other packages is easy, fam:
from typing import TYPE_CHECKING
if TYPE_CHECKING:
import some_package
def muh_func(some_arg: 'some_package.some_submodule.SomeType'): ... # <-- good!
# Instead, this is what Pydantic, "urllib3", and "xarray" are all doing. This is
# the "TYPE_CHECKING" forward reference antipattern:
if TYPE_CHECKING:
from some_package.some_submodule import SomeType
def muh_func(some_arg: 'SomeType'): ... # <-- *BAD*! gag me with a spork, Mork
Those two approaches may look identical. From the runtime perspective, those two approaches share nothing in common. They hate one other. TYPE_CHECKING evaluates to False at runtime, so @beartype (and other runtime type-checkers) can't see the imports hidden inside those if conditionals. All @beartype sees is:
'some_package.some_submodule.SomeType' in the former case. @beartype can fully resolve the SomeType type from this. @beartype is pleased and growls contentedly while rubbing its belly for scritches.'SomeType' in the latter case. That's... just not enough information. Like, at all. Throw @beartype a friggin' bone. @beartype can't resolve anything from that! @beartype growls and throws up.@beartype 0.21.0 will explicitly detect, warn about, and repair this antipattern across all beartype.claw import hooks. That's the glorious future. For now, @beartype 0.20.0 contents itself with just silently ignoring these problematic packages in beartype.claw import hooks. We do what we can. Sometimes, it isn't much.
@beartype doesn't hate these packages. We try to be tolerant of everyone's misinformed and bad opinions. In this case, we tolerate these packages by internally blacklisting them. We don't bother trying to subject their modules, types, or callables to runtime type-checking, because we can't. Their modules, types, and callables despise type-checking. What can you do? Nuthin'. We didn't make crazy; we can't control crazy; we just put crazy in a head lock and roll over it multiple times with our adipose-laden bodies until it stops moving.
Blacklisting these packages really improves the real-world usability of the beartype.claw.beartype_all() import hook in particular, which previously choked on imports from these packages. Since @beartype now automatically blacklists these packages, you no longer need to manually blacklist them yourself by listing these packages under the BeartypeConf(claw_skip_package_names=...) configuration option: e.g.,
from beartype.claw import beartype_all
# This default call to beartype_all()...
beartype_all()
# ...is now equivalent to this complicated logic, kinda. Yay!
#from beartype import BeartypeConf
#beartype_all(conf=BeartypeConf(claw_skip_package_names=(
# 'pydantic',
# 'urllib3',
# 'xarray',
#)))
@beartype 0.20.0: make all the bad stuff go away, QA daddy.
<sup>lol</sup>
@beartype 0.20.0 officially drops support for Python 3.8. Python 3.8 "recently" hits its official End-of-Life (EOL). Alright. Okay. It was ages ago, wasn't it? I still remember when Python 3.8 was the cool new kid who just wanted to come over and show you his $1,000 LEGO Millennium Falcon constructed entirely from deprecated type hints. Now, it's dead. Only my baldness remains. Python makin' me feel old over here.
This means that Python 3.8 now constitutes a security risk. More importantly, @beartype hates Python 3.8. Due to the Transitivity of Loathsomeness Principle (probably discovered by Pythagoras the Pythonic, the little-known balding stepchild of Pythagoras the Elder) your codebase now hates Python 3.8 too. Like a bad dream, feature loss is contagious.
<sup>$1000 bucks and 47 weeks of your youth: gone, just like @leycec when the issues pile up</sup>
@beartype 0.20.0 delivers less bugs – a lot less bugs. Turns out @beartype has been buggy for years. If nobody hits a bug for a decade but that bug still exists, does it make a sound when it crushes your codebase at 4:23AM on an icy Sunday? The answer is: "That sound is your dev team screaming in shared anguish."
@beartype 0.20.0 specifically:
from __future__ import annotations) with PEP 695 implicit type parameter instantiation (e.g., def muh_func[T](muh_arg: T) -> T: ...). Against all sanity, this somehow now works:from __future__ import annotations # <-- PEP 563, yo. it sucks, but you know best.
from beartype import beartype # <------- *GOOD*
@beartype
def muh_func[T](muh_arg: T) -> T: # <-- PEP 695 up in here, y'all!
return muh_arg
type aliases like you just don't care:from beartype import beartype # <------- *GOOD*
# PEP 695 type aliases, deeply nested because you no longer care about coworkers.
type ThatFeeling[T] = WhenYoureIn[T] | float
type WhenYoureIn[T] = TooDeep[T] | str
type TooDeep[T] = int | T
@beartype
def nuther_func(nuther_arg: TooDeep[complex]) -> TooDeep[bytes]:
return nuther_arg # <-- a type-check that is doomed to fail. it ain't so good
The above function signature is equivalent to this simpler, more readable, more maintainable, more debuggable, and yet somehow more boring signature:
@beartype
def nuther_func(nuther_arg: int | complex | str | float) -> int | bytes | str | float:
return nuther_arg # <-- we can now see this makes less sense than we thought
Boring is bad, though. That's clear. Simplicity doesn't count for much if you're bored all the time. Maximize non-boring even if it costs you your codebase, your career, and your future prospects of a happy family. Do what @leycec would do.
@beartype 0.20.0: because @beartype has to do what you say, even when it no longer wants to
<sup>the last thing your code will say before users cry on reddit</sup>
...to financially feed @leycec and his friendly @beartype through our ancient GitHub Sponsors profile that predates the existence of dinosaur-like AI chatbots. Come for the candid insider photos of a sordid and disreputable life in the Canadian interior; stay for the GitHub badge and warm feelings of general goodwill.
Cue hypnagogic rave music that encourages fiscal irresponsibility. :musical_note: :musical_keyboard: :notes:
...but nobody asked to leave, either. The Bear Beta Fan Club is GitHub's own Hotel California. The "Exit!" sign is poorly labelled. You keep getting roped back in with dubious reassurances that "things will be better this time."
This is that time.
@posita, @wesselb, @iamrecursion, @patrick-kidger, @langfield, @JelleZijlstra, @RobPasMue, @GithubCamouflaged, @kloczek, @uriyasama, @danielgafni, @JWCS, @rbroderi, @AlanCoding, @tvdboom, @crypdick, @jvesely, @komodovaran, @kaparoo, @MaximilienLC, @fleimgruber, @EtaoinWu, @alexoshin, @gabrieldemarmiesse, @James4Ever0, @NLPShenanigans, @rtbs-dev, @yurivict, @st--, @murphyk, @dosisod, @Rogdham, @alisaifee, @denisrosset, @damarro3, @ruancomelli, @jondequinor, @harshita-gupta, @jakebailey, @denballakh, @jaanli, @creatorrr, @msvensson222, @avolchek, @femtomc, @AdrienPensart, @jakelongo, @Artur-Galstyan, @ArneBachmann, @danielward27, @WeepingClown13, @rbnhd, @radomirgr, @rwiegan, @brettc, @spagdoon0411, @helderco, @paulwouters, @jamesbraza, @dcharatan, @kasium, @AdrienPensart, @sunildkumar, @peske, @mentalisttraceur, @awf, @PhilipVinc, @dcharatan, @empyrealapp, @rlkelly, @KyleKing, @skeggse, @RomainBrault, @deepyaman, @mzealey, @adamtheturtle, @Moosems, @minmax, @jedie, @pablovela5620, @thiswillbeyourgithub, @Logan-Pageler, @knyazer, @ilyapoz, @yuzhichang, @Fedezzab, @antonioan, @im-Kitsch, @mthramann, @fbartolic, @rgallardone, @frrad, @jonnyhyman, @jennydaman, @likewei92, @acec2127, @Glinte, @rudimichal, @woutdenolf, @PauloHMTeixeira
Beartype 0.20.0 Release Candidate 2 is... my Gods. Didn't I just do this two days ago? In hindsight, I should've waited two days. This had better be t
Beartype 0.20.0 Release Candidate 2 is... my Gods. Didn't I just do this two days ago? In hindsight, I should've waited two days. This had better be the final release of the @beartype 0.20.0 release cycle, because nobody wants to do this anymore. Let's goooooooooooooooooooo:
pip install --upgrade --pre beartype # <-- bugs begone
This final release candidate is entirely thanks to the tireless, peerless, and fearless Django wrangler @rudimichal (Michał Rudziński). He bled sweaty tears for this over at issue #488, where three weeks of haggling over objectively unreadable Django stacktraces culminated in... "this." It's best not to ask what "this" means. Just know you don't want to know. Some issue resolutions are best left unsung. Not all GitHub avatars wear capes.
Thanks again, @rudimichal! @beartype 0.20.0rc2 is for Django, the bugs we crushed along the way, and our shared sufferings.
<sup>aaaaaaaaaaand... We done.</sup>
…LEGO Millennium Falcon constructed entirely from deprecated type hints. Now, it's dead. Only my baldness remains. Python makin' me feel old over here.
Beartype 0.20.0 Release Candidate 1 gently rises aloft. The frigid storm blast dumping fifty litres of snow directly onto our cottage is no match for @beartype 0.20.0rc1. Like a hot-air balloon fuelled on hopes and dreams alone, @beartype 0.20.0rc1 asks the critical question: "How hopeful is your codebase that any of this actually works?"
Let our contagious dream of a higher-quality Python world infect your dreams, too. There's room enough on this hot-air balloon for all of us – and more than enough hot air:
pip install --upgrade --pre beartype # <-- bug off, bugs
<sup>pucci (the new @beartype mascot) gasps in wonder as your package collapses</sup>
This release comes courtesy these proud GitHub Sponsors, without whom @leycec's cats would currently be eating grasshoppers:
Thanks so much, masters of fintech and metrology.
<sup>The Masters of Fintech and Metrology. That's who.</sup>
And now for something... gothic, grotesque, and morbid!? :astonished: :open_mouth: :face_with_open_eyes_and_hand_over_mouth:
@beartype 0.20.0rc1 officially drops support for Python 3.8. Python 3.8 "recently" hits its official End-of-Life (EOL). Alright. It was ages ago. I still remember when Python 3.8 was the cool new kid who just wanted to come over and show you his $1,000 LEGO Millennium Falcon constructed entirely from deprecated type hints. Now, it's dead. Only my baldness remains. Python makin' me feel old over here.
This means that Python 3.8 now constitutes a security risk. More importantly, @beartype hates Python 3.8. Due to the Transitivity of Loathsomeness Principle (probably discovered by Pythagoras the Pythonic, the unknown balding stepchild of Pythagoras the Elder), your codebase now hates Python 3.8 too. Like a bad dream, feature loss is contagious.
<sup>$1000 bucks and 47 weeks of your youth: gone, just like @leycec when the issues pile up</sup>
@beartype 0.20.0rc1 delivers less bugs – a lot less bugs. Turns out @beartype has been buggy for years. If nobody hits a bug for a decade but that bug still exists, does it make a sound when it crushes your codebase at 4:23AM on an icy Sunday? The answer is: "That sound is your dev team screaming in shared anguish."
@beartype 0.20.0rc1 specifically:
from __future__ import annotations) with PEP 695 implicit type parameter instantiation (e.g., def muh_func[T](muh_arg: T) -> T: ...). Against all sanity, this somehow now works:from __future__ import annotations # <-- PEP 563, yo. it sucks, but you know best.
from beartype import beartype # <------- *GOOD*
@beartype
def muh_func[T](muh_arg: T) -> T: # <-- PEP 695 up in here, y'all!
return muh_arg
type aliases like you just don't care:from beartype import beartype # <------- *GOOD*
# PEP 695 type aliases, deeply nested because you no longer care about coworkers.
type ThatFeeling[T] = WhenYoureIn[T] | float
type WhenYoureIn[T] = TooDeep[T] | str
type TooDeep[T] = int | T
@beartype
def nuther_func(nuther_arg: TooDeep[complex]) -> TooDeep[bytes]:
return nuther_arg # <-- a type-check that is doomed to fail. it ain't so good
The above function signature is equivalent to this simpler, more readable, more maintainable, more debuggable, and yet somehow more boring signature:
@beartype
def nuther_func(nuther_arg: int | complex | str | float) -> int | bytes | str | float:
return nuther_arg # <-- we can now see this makes less sense than we thought
Boring is bad, though. That's clear. Simplicity doesn't count for much if you're bored all the time. Maximize non-boring even if it costs you your codebase, your career, and your future prospects of a happy family. Do what @leycec would do.
@beartype 0.20.0rc1: because @beartype has to do what you say, even when it no longer wants to
<sup>pucci isn't to blame for @beartype's poor decision-making... but your coworker might be</sup>
You are @beartype's last line of defence: @EtaoinWu, @Glinte, @rudimichal, @woutdenolf, @PauloHMTeixeira. You know who you are and what @beartype has done to your code.
Let us know if @beartype 0.20.0rc1 has done you less dirty. If so, we'll release the full-blown @beartype 0.20.0 in a week or fifteen. May Pucci the new @beartype mascot be with us all.
<sup>pucci curses the futility of her new job description</sup>
Beartype 0.20.0 Release Candidate 0 catapults out of your CRT monitor from the 90's that contains only four pounds of lead, across your mechanical key
Beartype 0.20.0 Release Candidate 0 catapults out of your CRT monitor from the 90's that contains only four pounds of lead, across your mechanical keyboard with the clacky keys and vibrant crumb trails, and into your lap. Startled, you shriek in fear. Then astonishment. Then back to fear. Trembling, your fingers reach for...
pip install --upgrade --pre beartype # <-- bugger the bugs
@beartype 0.20.0rc0 gurgles contentedly as you wipe the birthing fluids from its forehead. You choke back tears. In a moment of madness that borders on the divine, you pull the trigger. You update. You're in too deep now. The sunk cost fallacy you feel is real. Your devbox shudders. Your mechanical keyboard spills sugary soda all over itself. Your RSI-wracked mouse hand pulsates with the pre-install jitters. Surely the second coming of QA is at hand.
<sup>@beartype 0.20.0rc0: and you thought Gymnastics Turtle was weird</sup>
@beartype 0.20.0rc0 is brought to you by...
This release comes courtesy these proud GitHub Sponsors, without whom @leycec's cats would currently be eating grasshoppers:
Thanks so much, masters of fintech and metrology.
<sup>The Masters of Fintech and Metrology. That's who.</sup>
And now for something fishy.
@beartype 0.20.0rc0 COULD CATASTROPHICALLY BREAK EVERYTHING. This cannot be emphasized enough. Even all-caps bold style fails to highlight the severity of possible breakage. We implore you to update. We beg you to test. We pray that someone actually reads this. The userbase you save may be your own.
@beartype 0.20.0rc0 internally refactored our entire dynamic type-checking code generator – the beating heart of @beartype. Not a module was left untouched. Why? PEP 695-compliant subscripted type aliases. We don't know what that means either. Does it even matter anymore? In 2025, the truth itself is a mere mental construct of figurative... uhh. Wait. What were we talking about? Oh, right. Your code catastrophically breaking over @beartype's knee. Thus, we reiterate:
@beartype 0.20.0rc0 COULD CATASTROPHICALLY BREAK EVERYTHING. This cannot be emphasized enough, which is why we copy-pasted it again. The @beartype test suite still passes, but that doesn't mean much. We're not you. Your code knows better than we do. If something broke, it's probably your code.
<sup>the last thing your code will say before users cry on reddit</sup>
Absolutely! Well, surely. Well, probably. Well, possibly. Well, maybe.
@beartype 0.20.0rc0 brings to bear a whole new lineup of QA goodies. You never knew you needed these QA goodies until a small voice inside of you whispered:
"You do."
Before we get to some actual meaningful content in this changelog, though...
Left to my own devices, I just play video games and obsessively rummage around in the bike shed with PEP standards nobody cares about. This is why...
I implore you to vote in this GitHub forum poll. Yes. It's all true. User opinions always mattered, but now user opinions really matter. I can't pretend they don't exist anymore. For the first time ever, you can force me to do your questionable and unsavoury bidding. Tell me what to do this summer. Vote now. Vote often. Vote hard. But for the sake of the bugs crushing your workload, vote. :full_moon_with_face:
<sup>a vote for bob evil is a vote for @beartype 0.21.0</sup>
Iterable[...] + Container[...] = BBFFLs (Best Bear Friends for Life)@beartype now deeply type-checks the last remaining PEP 484- and 585-compliant container type hints in O(1) constant time, including:
collections.abc.Container[...] type hints.collections.abc.Iterable[...] type hints.collections.abc.Reversible[...] type hints.typing.Container[...] type hints.typing.Iterable[...] type hints.typing.Reversible[...] type hints.@beartype now type-checks exactly one item of containers annotated with general-purpose container type hints like Iterable[...] and Container[...] in O(1) constant time. How? Smarty bear pants. @beartype intelligently detects whether a container is:
list[str]), in which case a pseudorandom item of that
sequence is type-checked.set[int]), in which case only the first item of that
collection is type-checked.‼ Plum users may now dispatch on all of the above.
collections.abc.Iterable[...]is the Big One™, of course. This is the profit of depending on @beartype. You wait years for @leycec to do something. Finally, @leycec does a thing. Your code works. Users cheer. It is delicious.
<sup>beartype 0.20.0rc0 isn't laughing. beartype 0.20.0rc0 doesn't even know what's happening anymore...</sup>
@beartype now deeply type-checks PEP 484-compliant type variables (e.g., T = typing.TypeVar('T')) for a variety of common use cases. Mostly, this means type variables whose type-checking can be entirely decided at decoration time by the @beartype decorator.
Since deciding type-checking at decoration time is really fast, deeply type-checking type variables in these use cases is really fast as well. Like, O(1) fast. Like everything @beartype does, these type variables are cost-free. They don't cost anything, so you'd might as well use them. This probably marks the first serious attempt by any package to tackle type variables at runtime.
This support fully covers these common use cases:
MuhList[int] given the type class MuhList[T](list[T]): ...).MuhAlias[int] given the type alias type MuhAlias[T] = list[T] | T | int).Let's take a swan dive into the deep end of...
@beartype now propagates child hints up generic type hierarchies. Because @beartype values the cooperation of coworkers you barely convinced to use @beartype in the first place, @beartype propagates child hints efficiently, recursively, and (most importantly) safely. No generics are harmed in the propagation of child hints.
The proof is in the syntactically highlighted rainbow pudding. In this example, we bring the swift fist of justice to Python QA. First, we define a generic parametrized by a type variable T. Next, we annotate a function with a type hint created by subscripting that generic with the child hint int. Finally, @beartype does the rest by propagating that child hint int into that type variable T up the type hierarchy of that generic.
Behold! Boredom personified, yet you can't turn your lidded eyes away:
from beartype import beartype
from collections.abc import Container, Iterable, Iterator, Sequence
# Define a PEP 585-compliant generic satisfying both the
# "collections.abc.Iterable" and "Container" abstract base classes (ABCs). W00t!
@beartype
class SoDumbSoDelicious[T](Iterable[T], Container[T]):
def __init__(self, sequence: Sequence[T]) -> None:
self._sequence = sequence
def __contains__(self, obj: object) -> bool:
return obj in self._sequence
def __iter__(self) -> Iterator[T]:
return iter(self._sequence)
def __len__(self) -> int:
return len(self._sequence)
# Define a function accepting an instance of this generic constrained to contain
# *ONLY* integers. Yuppers. It's true. @beartype actually type-checks this now.
@beartype
def tastes_like_lard(yum: SoDumbSoDelicious[int]) -> int:
return next(iter(yum))
# Define delectable instances of this generic. Prove this isn't just crazy-talk!
love_me_some_lard = SoDumbSoDelicious((0xCAFE, 0xBABE))
gods_no_more_lard = SoDumbSoDelicious(('Cafe', 'Babe!'))
# Assert that calling this function with a valid parameter returns the
# expected value. You are the cafe. You are the lard. You knew you shouldn't
# have read that, but you kept on doing it. The punchline so wasn't worth it.
assert tastes_like_lard(love_me_some_lard) == 0xCAFE # <-- oh not that cafe
# Call this function with an invalid parameter, which then raises a
# type-checking violation. May the Gods strike me down if lard is bad for you!
tastes_like_lard(gods_no_more_lard) # <-- ...you will eat lard and like it
...which raises the expected type-checking violation:
Traceback (most recent call last):
File "/home/leycec/tmp/mopy.py", line 35, in <module>
tastes_like_lard(gods_no_more_lard) # <-- ...you will eat lard and like it
~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^
File "<@beartype(__main__.tastes_like_lard) at 0x7fce8b0828e0>", line 89, in tastes_like_lard
beartype.roar.BeartypeCallHintParamViolation: Function
__main__.tastes_like_lard() parameter yum=<__main__.SoDumbSoDelicious object at
0x7fce8b35d6d0> violates type hint __main__.SoDumbSoDelicious[int], as generic
superclass collections.abc.Iterable[T] of <class "__main__.SoDumbSoDelicious">
index 0 item str 'Cafe' not instance of int.
In other words, @beartype now "knows" that any object typed as SoDumbSoDelicious[int] should be an iterable container whose items are all integers. Under the furry hood, @beartype "knows" this by recursively replacing each instance of the type variable T with the child hint int within the generic type hierarchy of SoDumbSoDelicious .
In other words, @beartype now correctly propagates mappings from type variables parametrizing generic declarations (e.g., the T in class SoDumbSoDelicious[T](Iterable[T], Container[T]):) to the child hints subscripting usage of those generics (e.g., the int in SoDumbSoDelicious[int]). @beartype does this recursively for arbitrarily complex generic type hierarchies.
This broke my brain and took two full months of mostly unpaid volunteerism. That's why I still beg for money on GitHub Sponsors like that hobo chugging Duck wine out of a cardboard box on your commute to work every day. Like the hobo, I had fun. Like the hobo, I had the urge to sleep in the gutter. This feature was so hard I had to refactor the entire @beartype codebase to support it – including @beartype's totally-not-fragile dynamic type-checking code generator that I avoid touching at all costs. That's how totally-not-fragile it is. It's the sort of poorly documented 10,074-line code dump you see prefixed with stultifying ASCII art banners like:
######### LUCK DRAGON EATS YOUR LUNCH, THEN HICCUPS?!? #########
# Here thar be dragons, code matey. Arr. *hiccup* #
# ⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⣀⣀⣤⣤⣤⣤⡼⠀⢀⡀⣀⢱⡄⡀⠀⠀⠀⢲⣤⣤⣤⣤⣀⣀⡀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀ #
# ⠀⠀⠀⠀⠀⠀⠀⠀⠀⣠⣴⣾⣿⣿⣿⣿⣿⡿⠛⠋⠁⣤⣿⣿⣿⣧⣷⠀⠀⠘⠉⠛⢻⣷⣿⣽⣿⣿⣷⣦⣄⡀⠀⠀⠀⠀⠀⠀⠀⠀ #
# ⠀⠀⠀⠀⠀⠀⢀⣴⣞⣽⣿⣿⣿⣿⣿⣿⣿⠁⠀⠀⠠⣿⣿⡟⢻⣿⣿⣇⠀⠀⠀⠀⠀⣿⣿⣿⣿⣿⣿⣿⣿⣟⢦⡀⠀⠀⠀⠀⠀⠀ #
# ⠀⠀⠀⠀⠀⣠⣿⡾⣿⣿⣿⣿⣿⠿⣻⣿⣿⡀⠀⠀⠀⢻⣿⣷⡀⠻⣧⣿⠆⠀⠀⠀⠀⣿⣿⣿⡻⣿⣿⣿⣿⣿⠿⣽⣦⡀⠀⠀⠀⠀ #
# ⠀⠀⠀⠀⣼⠟⣩⣾⣿⣿⣿⢟⣵⣾⣿⣿⣿⣧⠀⠀⠀⠈⠿⣿⣿⣷⣈⠁⠀⠀⠀⠀⣰⣿⣿⣿⣿⣮⣟⢯⣿⣿⣷⣬⡻⣷⡄⠀⠀⠀ #
# ⠀⠀⢀⡜⣡⣾⣿⢿⣿⣿⣿⣿⣿⢟⣵⣿⣿⣿⣷⣄⠀⣰⣿⣿⣿⣿⣿⣷⣄⠀⢀⣼⣿⣿⣿⣷⡹⣿⣿⣿⣿⣿⣿⢿⣿⣮⡳⡄⠀⠀ #
# ⠀⢠⢟⣿⡿⠋⣠⣾⢿⣿⣿⠟⢃⣾⢟⣿⢿⣿⣿⣿⣾⡿⠟⠻⣿⣻⣿⣏⠻⣿⣾⣿⣿⣿⣿⡛⣿⡌⠻⣿⣿⡿⣿⣦⡙⢿⣿⡝⣆⠀ #
# ⠀⢯⣿⠏⣠⠞⠋⠀⣠⡿⠋⢀⣿⠁⢸⡏⣿⠿⣿⣿⠃⢠⣴⣾⣿⣿⣿⡟⠀⠘⢹⣿⠟⣿⣾⣷⠈⣿⡄⠘⢿⣦⠀⠈⠻⣆⠙⣿⣜⠆ #
# ⢀⣿⠃⡴⠃⢀⡠⠞⠋⠀⠀⠼⠋⠀⠸⡇⠻⠀⠈⠃⠀⣧⢋⣼⣿⣿⣿⣷⣆⠀⠈⠁⠀⠟⠁⡟⠀⠈⠻⠀⠀⠉⠳⢦⡀⠈⢣⠈⢿⡄ #
# ⣸⠇⢠⣷⠞⠁⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠙⠻⠿⠿⠋⠀⢻⣿⡄⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠈⠙⢾⣆⠈⣷ #
# ⡟⠀⡿⠁⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⣴⣶⣤⡀⢸⣿⠇⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢻⡄⢹ #
# ⡇⠀⠃⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢸⡇⠀⠈⣿⣼⡟⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠈⠃⢸ #
# ⢡⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠈⠻⠶⣶⡟⠋⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⡼ #
# ⠈⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢀⡾⠋⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠁ #
# ⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢸⡁⢠⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀ #
# ⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢀⣿⣿⣼⣀⣠⠂⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀ #
# Dragons ahoy, code matey. Swab the Steam Deck. Arr. #
######### ASCII ART MEANS SWEAT, TEARS, AND CI FAILURE #########
It's likely there are unresolved edge cases I'm blissfully unaware of. If you hit one of these golden landmines, please submit an issue. I'll promptly resolve everything or collapse on my keyboard trying. :cold_sweat:
‼ Plum users may now dispatch on subscripted generics. This is the profit of depending on @beartype. You wait years for @leycec to do something. Finally, @leycec does a thing. Exhaustedly, you pump your hand in the sign of victory. You are vindicated... yet you feel empty.
<sup>awkward life moments (brought to you by @beartype)</sup>
@beartype now propagates child hints up generic type aliases, too. This is genuinely cool. Like, "cool kids" cool. Generic type aliases are kinda like functions or a full-blown templating engine – except for type hints. If you've ever found yourself copy-pasting one stupidly long type hint into another, you've realized you're violating the Don't Repeat Yourself (DRY) principle and are now off the deep end of QA. Thus:
# Instead of copy-pasting hellish type hints surely spawned in the Ninth Circle
# like this...
PygmentsStringToken = list[typing.Union[
tuple[str | collections.abc.Callable[typing.Concatenate[object, object, ...], object], ...],
tuple[str | pygments.token._TokenType[str], ...],
typing.Annotated[collections.abc.Collection[str], beartype.vale.IsInstance[pygments.lexer.include]],
]]
PygmentsBytesToken = list[typing.Union[
tuple[bytes | collections.abc.Callable[typing.Concatenate[object, object, ...], object], ...],
tuple[bytes | pygments.token._TokenType[bytes], ...],
typing.Annotated[collections.abc.Collection[bytes], beartype.vale.IsInstance[pygments.lexer.include]],
]]
# ...just define a single generic type alias like this...
type PygmentsToken[T] = list[typing.Union[
tuple[T | collections.abc.Callable[typing.Concatenate[object, object, ...], object], ...],
tuple[T | pygments.token._TokenType[T], ...],
typing.Annotated[collections.abc.Collection[str], beartype.vale.IsInstance[pygments.lexer.include]],
]]
# ...then subscript that alias with child hints. Look, code metrics! No DRY.
PygmentsStringToken = PygmentsToken[str]
PygmentsBytesToken = PygmentsToken[bytes]
In this example, PygmentsToken may not look like a function – but it pretty much is. It's a "function" that generates a new type hint from a standardized template every time you subscript it with a new child hint.
So what's the catch? We hope you don't mind requiring Python ≥ 3.12 by dropping support for Python ≤ 3.11. Because... that's the catch. If you try to define even a single type alias in a single submodule of your package under Python ≤ 3.11, your entire app unceremoniously blows up with a fatal SyntaxError: invalid syntax exception. Good luck with that.
@beartype 0.20.0rc0: because your users hate Python ≤ 3.11, too.
<sup>barbarian code never got type-checked by @beartype</sup>
I don't even know what "thrumming" is, but I'm pretty sure that's what happens to your sinews when you combine the fearsome power of subscripted generics and subscripted type aliases. The coworker to your right is already cowering. Good. That feeling is good. Soon, they will all kneel! </muhaha— *choking*>
Behold! A subscripted type alias propagating its child hint onto a subscripted generic. Why? Because your QA pipeline wasn't complicated enough and you now need to justify your position to those new bastards in suits nice HR spokespeople:
from beartype import beartype
from collections.abc import Container, Iterable, Iterator, Sequence
# Define the same PEP 585-compliant generic as above. Booooooooring.
@beartype
class SoDumbSoDelicious[T](Iterable[T], Container[T]):
def __init__(self, sequence: Sequence[T]) -> None:
self._sequence = sequence
def __contains__(self, obj: object) -> bool:
return obj in self._sequence
def __iter__(self) -> Iterator[T]:
return iter(self._sequence)
def __len__(self) -> int:
return len(self._sequence)
# Define a PEP 695-compliant type alias unifying this generic with other stuff.
# Look... *I* don't know. You're the genius here. You'll defly get a raise at
# work if you keep pushing out quality code like this.
type MaybeSoDumbSoDelicious[T] = T | MaybeSoDumbSoDelicious[T] | None
# Define a function accepting either an integer, an instance of this generic
# constrained to contain *ONLY* integers, or "None". @beartype type-checks this,
# because @beartype has no say in the matter. @beartype has to do what you say.
# This is why @beartype feels great sadness in the Autumn.
@beartype
def maybe_tastes_like_lard(yum: MaybeSoDumbSoDelicious[int]) -> int:
return next(iter(yum))
# Define delectable instances of this generic. Prove this isn't just crazy-talk!
love_me_some_lard = SoDumbSoDelicious((0x1331, 0xC001))
gods_no_more_lard = SoDumbSoDelicious(('Leet', 'Cool!'))
# Assert that calling this function with a valid parameter returns the
# expected value. You are the cafe. You are the lard. You knew you shouldn't
# have read that, but you kept on doing it. The punchline so wasn't worth it.
assert maybe_tastes_like_lard(love_me_some_lard) == 0x1331 # <-- oh not that cafe
# Call this function with an invalid parameter, which then raises a
# type-checking violation. May the Gods strike me down if lard is bad for you!
maybe_tastes_like_lard(gods_no_more_lard) # <-- ...you will eat lard and like it
...which raises the expected type-checking violation:
Traceback (most recent call last):
File "/home/leycec/tmp/mopy.py", line 42, in <module>
maybe_tastes_like_lard(gods_no_more_lard) # <-- ...you will eat lard and like it
~~~~~~~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^
File "<@beartype(__main__.maybe_tastes_like_lard) at 0x7f89162fa8e0>", line 94, in maybe_tastes_like_lard
beartype.roar.BeartypeCallHintParamViolation: Function
__main__.maybe_tastes_like_lard() parameter yum=<__main__.SoDumbSoDelicious
object at 0x7f89165c5810> violates type hint MaybeSoDumbSoDelicious[int], as
<class "__main__.SoDumbSoDelicious"> <__main__.SoDumbSoDelicious object at
0x7f89165c5810>:
* Not int or <class "builtins.NoneType">.
* Generic superclass collections.abc.Iterable[T] of <class
"__main__.SoDumbSoDelicious"> index 0 item str 'Leet' not instance of int.
...which only goes to show that @beartype now knows everything. Lo! It is known.
<sup>@beartype is getting bad vibes from trumpy</sup>
One ill-fated morning, you realise with a gnawing horror... You've run out of coffee. The Pop-Tarts® box is empty. There's no reason to get up anymore. You greet the watery Sun with a thousand-yard stare half-baked beyond the void of space. Yet, through crusty eyes, you think to yourself:
Can I compare whether one subscripted generic is a subhint of (i.e., both commensurable with and narrower than) another subscripted generic? If I can, why would I want to do that? Is this what life without coffee and Pop-Tarts® is like for billions around the world even today!?!?
I don't know why, but unspecified people <sup>okay, it's @patrick-kidger and @wesselb</sup> want to compare subscripted generics. I smell academia and a burgeoning career built on the shuddering back of @beartype. You might be one of these people or a person like these people. But, let's be honest... you're probably not. You're wondering why you're still reading this and rapidly realizing there's no good answer to that question. Some questions are bad.
Let's pretend you're one of these people. Rejoice! @beartype now decides the least trivial computational puzzle in the field of type systems, because @leycec couldn't bear to see that unresolved [Bug] status for another year:
>>> from beartype.door import is_subhint # <-- it's baaaaaaack
>>> from collections.abc import Sequence
>>> from typing import Generic, TypeVar
# Define some type variables like it's 2017.
>>> S = TypeVar('S')
>>> T = TypeVar('T')
>>> T_sequence = TypeVar('T_sequence', bound=Sequence)
# Define some parametrized generics. Pretend this means something.
>>> class GenericST(Generic[S, T]): pass
>>> class GenericSInt(Pep484GenericST[S, int]): pass
# Decide whether these generics are related or not, especially when subscripted
# by child hints. You don't know why you want to decide this. You just do.
# You've gotta. You're compelled by inner demons to go beyond the pale
# crenellations of normalcy, beyond even the liminal subspaces of QA. WUT?!?
>>> is_subhint(Pep484GenericSInt, Pep484GenericST)
True # <-- ...okay
>>> is_subhint(Pep484GenericSInt, Pep484GenericST[int, int])
False # <-- sure, buddy
>>> is_subhint(Pep484GenericSInt[int], Pep484GenericST)
True # <-- i'm not your buddy, pal
>>> is_subhint(Pep484GenericSInt[int], Pep484GenericST[S, T_sequence])
False # <-- whatever you say, bear boss
>>> is_subhint(Pep484GenericSInt[list], Pep484GenericST[T_sequence, object])
True # <-- pretty sure i no longer know what's happening
>>> is_subhint(Pep484GenericSInt[list], Pep484GenericST[Sequence, Any])
True # <-- seems legit if i squint at it
>>> is_subhint(Pep484GenericSInt[str], Pep484GenericST[T_sequence, S])
True # <-- it's too good to be true
>>> is_subhint(Pep484GenericSInt[Sequence], Pep484GenericST[list, object])
False # <-- finally, a falsehood exposed
>>> is_subhint(Pep484GenericSInt[T_sequence], Pep484GenericST)
True # <-- yeah, right, @beartype! as if
I'm confident you could profitably author multiple doctoral theses strung out across multiple poorly remunerated grad students who hate themselves almost as much as you do by just addressing, redressing, and endlessly rehashing this single issue. Papermill careers are built on the boneless backs of issues like this.
Originally, I wanted to bludgeon everyone in attendance with a tiresome essay doing just that. In the bitter end, even the mere thought of tiring everyone tires me beyond the event horizon of exhaustion.
Still, boredom is its own reward. I'll say that @beartype has probably invented the optimally efficient algorithm for deciding this problem. Nobody cares, of course. Even I am lacklustre about this whole thing.
But a non-recursive depth-first search (DFS) is a glorious self-flagellation that few ever attempt and even fewer survive. This DFS exhibits:
O(1) constant time complexity. Pump that fist!O(jk) quadratic time complexity, where:
j is the largest number of child type hints transitively subscripting an unerased pseudo-superclass of the first generic passed to is_subhint(). You don't even want to know what "unerased pseudo-superclass" means.k is the total number of transitive pseudo-superclasses of the same generic. Ditto.Because the DFS is non-recursive, it's stupidly fast, unreadable, undebuggable, and unmaintainable. This is why we @beartype:
...so that all the suffering is concentrated in one place.
<sup>left: parametrized generics. right: ...is that @leycec?!?</sup>
Of course, @leycec is lazy. @beartype still lacks general-purpose support for type-checking type variables at call time. This means @beartype still ignores type-checking violations involving mismatching types across type variables like:
def muh_func[T](muh_arg: T) -> list[T]:
return ['this is busted', "but you'll never know", 'cause @beartype dumb.']
# Beartype should raise a type-checking violation here, as the list returned by
# this function is a list of strings rather than a list of integers. Sadly,
# beartype currently thinks this is fine and does nothing, much like our cats.
muh_func(0xDEADCODE)
@beartype 0.20.0rc0: shrugging apathetically while your code burns
<sup>the answer may shock you</sup>
@beartype now tolerates these extremely popular third-party packages that hate @beartype ≤ 0.19.0 (and other runtime type-checkers, too):
urllib3.xarray.Yes, these packages hate @beartype (and other runtime type-checkers, too). The irony is especially rich in Pydantic's case, because Pydantic itself is a runtime type-checker. This must be what happens when you go full-Rust.
These packages all doubled down on the typing.TYPE_CHECKING forward reference antipattern, which @beartype 0.21.0 will have a lot to say about. Until then, this is "Leycec's Abbreviated Notes on the Antipattern That Destroys True Goodness and Heroism":
# This is what PEP 484, PEP 563, and @beartype all want you to do. Forward
# referencing external types defined in other packages is easy, fam:
from typing import TYPE_CHECKING
if TYPE_CHECKING:
import some_package
def muh_func(some_arg: 'some_package.some_submodule.SomeType'): ... # <-- good!
# Instead, this is what Pydantic, "urllib3", and "xarray" are all doing. This is
# the "TYPE_CHECKING" forward reference antipattern:
if TYPE_CHECKING:
from some_package.some_submodule import SomeType
def muh_func(some_arg: 'SomeType'): ... # <-- *BAD*! gag me with a spork, Mork
Those two approaches may look identical. From the runtime perspective, those two approaches share nothing in common. They hate one other. TYPE_CHECKING evaluates to False at runtime, so @beartype (and other runtime type-checkers) can't see the imports hidden inside those if conditionals. All @beartype sees is:
'some_package.some_submodule.SomeType' in the former case. @beartype can fully resolve the SomeType type from this. @beartype is pleased and growls contentedly while rubbing its belly for scritches.'SomeType' in the latter case. That's... just not enough information. Like, at all. Throw @beartype a friggin' bone. @beartype can't resolve anything from that! @beartype growls and throws up.@beartype 0.21.0 will explicitly detect, warn about, and repair this antipattern across all beartype.claw import hooks. That's the glorious future. For now, @beartype 0.20.0 contents itself with just silently ignoring these problematic packages in beartype.claw import hooks. We do what we can. Sometimes, it isn't much.
@beartype doesn't hate these packages. We try to be tolerant of everyone's misinformed and bad opinions. In this case, we tolerate these packages by internally blacklisting them. We don't bother trying to subject their modules, types, or callables to runtime type-checking, because we can't. Their modules, types, and callables despise type-checking. What can you do? Nuthin'. We didn't make crazy; we can't control crazy; we just put crazy in a head lock and roll over it multiple times with our adipose-laden bodies until it stops moving.
Blacklisting these packages really improves the real-world usability of the beartype.claw.beartype_all() import hook in particular, which previously choked on imports from these packages. Since @beartype now automatically blacklists these packages, you no longer need to manually blacklist them yourself by listing these packages under the BeartypeConf(claw_skip_package_names=...) configuration option: e.g.,
from beartype.claw import beartype_all
# This default call to beartype_all()...
beartype_all()
# ...is now equivalent to this complicated logic, kinda. Yay!
#from beartype import BeartypeConf
#beartype_all(conf=BeartypeConf(claw_skip_package_names=(
# 'pydantic',
# 'urllib3',
# 'xarray',
#)))
@beartype 0.20.0rc0: make all the bad stuff go away, QA daddy.
<sup>lol</sup>
...to financially feed @leycec and his friendly @beartype through our ancient GitHub Sponsors profile that predates the existence of dinosaur-like AI chatbots. Come for the candid insider photos of a sordid and disreputable life in the Canadian interior; stay for the GitHub badge and warm feelings of general goodwill.
Cue hypnagogic rave music that encourages fiscal irresponsibility. :musical_note: :musical_keyboard: :notes:
...but nobody asked to leave, either. The Bear Beta Fan Club is GitHub's own Hotel California. The "Exit!" sign is poorly labelled. You keep getting roped back in with dubious reassurances that "things will be better this time."
This is that time.
@posita, @wesselb, @iamrecursion, @patrick-kidger, @langfield, @JelleZijlstra, @RobPasMue, @GithubCamouflaged, @kloczek, @uriyasama, @danielgafni, @JWCS, @rbroderi, @AlanCoding, @tvdboom, @crypdick, @jvesely, @komodovaran, @kaparoo, @MaximilienLC, @fleimgruber, @EtaoinWu, @alexoshin, @gabrieldemarmiesse, @James4Ever0, @NLPShenanigans, @rtbs-dev, @yurivict, @st--, @murphyk, @dosisod, @Rogdham, @alisaifee, @denisrosset, @damarro3, @ruancomelli, @jondequinor, @harshita-gupta, @jakebailey, @denballakh, @jaanli, @creatorrr, @msvensson222, @avolchek, @femtomc, @AdrienPensart, @jakelongo, @Artur-Galstyan, @ArneBachmann, @danielward27, @WeepingClown13, @rbnhd, @radomirgr, @rwiegan, @brettc, @spagdoon0411, @helderco, @paulwouters, @jamesbraza, @dcharatan, @kasium, @AdrienPensart, @sunildkumar, @peske, @mentalisttraceur, @awf, @PhilipVinc, @dcharatan, @empyrealapp, @rlkelly, @KyleKing, @skeggse, @RomainBrault, @deepyaman, @mzealey, @adamtheturtle, @Moosems, @minmax, @jedie, @pablovela5620, @thiswillbeyourgithub, @Logan-Pageler, @knyazer, @ilyapoz, @yuzhichang, @Fedezzab, @antonioan, @im-Kitsch, @mthramann, @fbartolic, @rgallardone, @frrad, @jonnyhyman, @jennydaman, @likewei92, @acec2127
@beartype 0.19.0 gently glides into your CI workflow for a ~~crash~~ miracle landing. Engines go *brrrrrrrr.*
@beartype 0.19.0 gently glides into your CI workflow for a crash miracle landing. Engines go brrrrrrrr.
<sup>@beartype 0.19.0 narrowly avoids the grazing sheep in this terrifying metaphor.</sup>
@beartype 0.19.0 invites you to experience either the future of QA or a new catastrophe for QA – all from the comfort of your (t)rusty keyboard. It now thrums with untold power and the lurid afterglow of our out-of-control release cycle.
pip install --upgrade beartype # <-- engines hit full throttle, stomach hits full empty
@beartype 0.19.0 is proudly brought to you by...
This release comes courtesy these proud GitHub Sponsors, without whom @leycec's cats would currently be eating grasshoppers:
Thanks so much, masters of fintech and metrology.
<sup>The Masters of Fintech and Metrology. That's who.</sup>
<sup>Probably, a whole lot. Hopefully, a whole little. The truth lies in the middle.</sup>
@beartype 0.19.0 sidles up to your codebase in its blind spot with something suspicious in its paws. Questionable new features include:
beartype.door.infer_hint(): let BeartypeAI™ write your type hints for you, because you no longer have der Wille zur Macht to constantly deal with all this [redacted pejorative]:
# I've got a crazy object here, @beartype. What's the crazy type hint that
# matches my crazy object? This is gonna really suck. I can *FEEL* it coming
# through my monitor tonight.
>>> beartype.door.infer_hint(pygments.lexers.PythonLexer().tokens["root"])
list[typing.Union[tuple[str | collections.abc.Callable[
typing.Concatenate[object, object, ...], object], ...], tuple[str |
pygments.token._TokenType[str], ...], typing.Annotated[
collections.abc.Collection[str], beartype.vale.IsInstance[
pygments.lexer.include]]]] # <-- I have no idea. Neither does that cute intern.
beartype.claw.beartype_all() + BeartypeConf(claw_skip_package_names): a single one-liner type-checks your entire app stack at runtime or test-time while ignoring problematic third-party packages that inexplicably hate @beartype for "reasons":
beartype_all(conf=BeartypeConf(claw_skip_package_names=('bad_package', 'dumb.submodule')))
**kwargs: int | str: @beartype type-checks annotated variadic keyword arguments! yay! uhh... wait. wasn't @beartype always doing that? these emoji suggest otherwise: :smile: → :sob:
def i_am_simply_shocked(**kwargs: int | str): ... # <-- @beartype actually checks this now
Deeper O(1) type-checking. @beartype 0.19.0 now deeply type-checks type hints like:
frozenset[...].set[...].collections.ChainMap[...].collections.Counter[...].collections.deque[...].collections.abc.Collection[...].collections.abc.ItemsView[...].collections.abc.KeysView[...].collections.abc.MutableSet[...].collections.abc.Set[...].collections.abc.ValuesView[...].typing.AbstractSet[...].typing.ChainMap[...].typing.Collection[...].typing.Counter[...].typing.Deque[...].typing.FrozenSet[...].typing.ItemsView[...].typing.KeysView[...].typing.MutableSet[...].typing.Set[...].typing.ValuesView[...].Shallow O(1) type-checking support for exciting (yet wildly unpopular) PEP standards that nobody uses. @beartype 0.19.0 now quietly ignores these PEPs without throwing up everywhere:
def muh_decorator_closure(*args: P.args, **kwargs: P.kwargs):).Ts = typing.TypeVarTuple('Ts')).**kwargs typing (e.g., def muh_kwargs_func(**kwargs: typing.Unpack[MuhTypedDict]]):).Official multiprocessing support. @beartype 0.19.0 now officially supports fork-based distributed workloads based on the awful pickle module. :rofl:
Third-party decorator integration. @beartype 0.19.0 now officially supports popular Just-in-Time (JIT) decorators for machine learning (ML) like:
@equinox.filter_jit.@jax.jit.@numba.njit.Python 3.13 + --disable-gil + --enable-experimental-jit. Pinch me, I must be hyperventilating into a paper bag again.
Sane build toolchain: from setuptools + setup.py <sup> :vomiting_face: </sup> to Hatch + pyproject.toml. <sup> :clinking_glasses: </sup>
Sane publishing toolchain: from antiquated GitHub Actions tokens <sup> :vomiting_face: </sup> to PyPI-specific "Trusted Publishers". <sup> :clinking_glasses: </sup>
Critical bugs resolutions: blah, blah. Who cares. I'm tired. So are you.
<sup>@beartype 0.19.0 feature list mollifies even the unruly pirate crowd in the back</sup>
infer_hint(): Introducing BeartypeAI™, Your Chummy QA PalChummy Unpaid QA Pal BeartypeAI™ is on the job and grumbling already about union overtime. Because your team hates type hints (and you're reluctantly starting to admit they might be onto something), BeartypeAI™ does what nobody else wants to do. Authoring type hints is a thankless janitorial fetch quest that smells bad and consumes your last will to code.
Allow our new beartype.door.infer_hint() function to automate your ongoing stomache pain away. Type hints may be like that kidney stone the size of your mother-in-law's big head, but that's no reason to curl up on a gurney clutching your side in blinding agony. But first:
"What are type hints, really – aside from the second-worst ongoing maintenance nightmare in Python next to
pyproject.tomlsemantic versioning dependency bumps?"
Type hints are the most compact description of the internal structure of your objects. If you know the type hint of an object, you know the object better than the object knows itself. Type hints are the ultimate self-documentation. Unlike docstrings, type hints never lie or @beartype breaks your app. Type hints are both human-readable and machine-readable. They're literally the only thing that is.
Many type hints are trivial to write. All of us can sling around breezy list[int] | None type hints while yawning. It's not impressive. My cats can write that type hint with one sleepless eye open. Seriously. Why do cats sleep with one eye open, anyway? Doesn't that kinda defeat the purpose of... I dunno, sleeping? Must suck to be a paranoid cat. Uhhh. Back to the discussion.
Some type hints, however, are non-trivial. You can't write them. Nobody can. They contain more square brackets than an 80's ASCII roguelike with an understated name like Death Gehenna or Eternal Furnaces of NetSwargy. When your type hint looks like this, the end of code maintainability cannot be far:
<sup>that feeling when your type hints resemble incomprehensible toddlers</sup>
Moreover, you don't even know the internal structure of most objects. Somebody else wrote those objects. They forgot how those objects worked a hot minute after clocking out at 4:12AM seven days deep into a crunch-time death march last January. They documented how those objects worked, but their documentation doesn't make sense and lies about everything. Now nobody knows how those objects work.
But what if somebody did know how those objects work? What if somebody knew Python better than Python knew itself? Introducing... somebody.
infer_hint(): Deep Introspection for the Deep Code DiverLet @beartype ease your weary burden, traveller. It is dangerous to go alone:
# Crazy object you could understand. But... ain't nobody got that kinda time.
>>> from pygments.lexers import PythonLexer
>>> root_tokens = PythonLexer().tokens["root"]
# I've got a crazy object here, @beartype. What's the crazy type hint that
# matches my crazy object? This is gonna really suck. I can *FEEL* it coming
# through my monitor tonight.
>>> from beartype.door import infer_hint
>>> infer_hint(root_tokens)
list[ # <-- what could possibly go wrong?
typing.Union[ # <-- sucky stuff starts
tuple[str | collections.abc.Callable[typing.Concatenate[object, object, ...], object], ...], # <-- sucky stuff intensifies
tuple[str | pygments.token._TokenType[str], ...], # <-- so much sucky stuff
typing.Annotated[collections.abc.Collection[str], beartype.vale.IsInstance[pygments.lexer.include]] # <-- go to heck, typing!
] # <-- a pox on your square brackets
] # <-- i have no idea and neither do you
...uhh. If you say so, @beartype. I guess? </weeps_in_square_bracket_hell>
<sup>codebase narrowly dodges another inexpert potshot from pygments</sup>
beartype.door.infer_hint() (i.e., the algorithm hereafter known simply as BeartypeAI™) knows all about deep introspection of arbitrarily complex objects. Here's what BeartypeAI™ knows:
BeartypeAI™: "I know that your type hints kinda suck. Wait... where are your type hints? Oh, Gods. You don't type hint. I'm panicking. I'm panicking."
You: "Tell my team something my team don't know, BeartypeAI™. We hate type hints. So we don't type hint. We code instead. You should try it sometime. But... hey, aren't you a type-checking bear? Can you even code with those fat paws?"
BeartypeAI™: "Hold my QA beer."
BeartypeAI™ is here to tell you something you don't know and wouldn't care about even if you did.
BeartypeAI™ is here to write your type hints for you. Why? Because you hate type hints. Just:
beartype.door.infer_hint() arbitrarily complex objects.It's impossible to unpack how much madness is happening inside BeartypeAI™. Let's try anyway.
>>> from beartype.door import infer_hint # <-- all your dreams begin here
# Show me the type hint describing a useless object, @beartype!
>>> infer_hint(object())
<class 'object'> # <-- makes sense
# Show me the type hint describing a useless type, @beartype!
>>> infer_hint(object)
type[object] # <-- so. cool.
# Show me the type hint describing a list of strings, @beartype!
>>> infer_hint(['expose', 'extreme', 'explosions!',])
list[str] # <-- hole in one
# Show me the type hint describing a tuple of crazy stuff, @beartype!
>>> infer_hint((b'heh', [0xBEEEEEEEF, 'ohnoyoudont',]))
tuple[bytes, list[int | str]] # <-- no idea, but i trust it
# Show me the type hint describing an insane recursive list, @beartype!
>>> recursive_list = ['this is fine', b'but...',]
>>> recursive_list.append(recursive_list)
>>> infer_hint(recursive_list)
list[str | bytes | beartype.door._func.infer.inferhint.BeartypeInferHintContainerRecursion] # <-- just go with it
<sup>BeartypeAI™ pounds back another as your git log explodes in the distance</sup>
We've all been there. Some "genius"-tier wise guy devbro invented his own homebrew pure-Python collection called WeirdoCustomList without subclassing a standard collections.abc abstract base class. Sure, they could have just subclassed collections.abc.MutableSequence to write their special-needs alternative to the builtin list type. That would have been too easy. They're a masochist, so they wrote everything from scratch.
Homebrew collections are more common than you think. They're friggin' everywhere! They're multiplying like meat flies! The cat's choking on bloody homebrow collections! Look above, for example. See that nasty typing.Annotated[collections.abc.Collection[str], IsInstance[pygments.lexer.include]] type hint that BeartypeAI™ wrote for you? Yeah.
That's right. The public pygments.lexer.include type is actually a homebrew collection. They thought they were being smart. Sadly, they were being dumb. Because they wrote a homebrew collection from scratch, their collection type is unsubscriptable. You can't subscript it with child type hints like with list[str], so you can't use their collection type as a type hint factory to write type hints, so you can't actually validate their homebrew collection. In fact, you can't validate any homebrew collections.
...until now. BeartypeAI™ knows all about homebrew collections. BeartypeAI™ knows that you can actually validate homebrew collections – but only if you write a custom beartype validator leveraging the PEP 593-compliant typing.Annotated[...] type hint factory in concert with the @beartype-specific beartype.vale.IsInstance[...] validator. Please don't do this manually. You value your precious life force that is leaking all over your keyboard as we speak.
That's what the typing.Annotated[collections.abc.Collection[str], IsInstance[pygments.lexer.include]] type hint is all about. BeartypeAI™ correctly detected that this homebrew collection is actually just an instance of the pygments.lexer.include class that is externally usable as a collection of strings.
Let's get more explicit. Nobody understands pygments – not even pygments. Instead, consider...
<sup>BeartypeAI™ casually flings itself above another picturesque yet ultimately incomprehensible codebase</sup>
It's... it's hideous!
from beartype.door import infer_hint
from collections.abc import Iterable, Iterator
# Define a weirdo custom list.
class WeirdoCustomList(object):
'''
Weirdo custom list. The one. The only.
Weirdo custom list pretends to mean no harm. Weirdo custom list is
lonely at night and only wants to be snuggle-friends. *How could you
refuse weirdo custom list in its example of need?*
'''
def __init__(self, items: list) -> None: self._items = items
def __contains__(self, item: object) -> bool: return item in self._items
def __iter__(self) -> Iterator: return iter(self._items)
def __len__(self) -> int: return len(self._items)
def __getitem__(self, index: int) -> object: return self._items[index]
def __reversed__(self) -> Iterator: return reversed(self._items)
def count(self, item: object) -> int: return self._items.count(item)
def index(self, *args, **kwargs) -> int:
return self._items.index(*args, **kwargs)
def __delitem__(self, index: int) -> None: del self._items[index]
def __setitem__(self, index: int, item: object) -> None:
self._items[index] = item
def __iadd__(self, item: object) -> object: self._items += item
def append(self, item: object) -> None: self._items.append(item)
def clear(self) -> None: self._items.clear()
def extend(self, items: Iterable) -> None: self._items.extend(items)
def insert(self, index: int, item: object) -> None:
self._items.insert(index, item)
def pop(self, *args, **kwargs) -> object:
return self._items.pop(*args, **kwargs)
def remove(self, item: object) -> None: self._items.remove(item)
def reverse(self) -> None: self._items.reverse()
# Infer the type hint for a weirdo custom list of strings.
print(infer_hint(WeirdoCustomList([
'No way,', '@beartype.', 'No.', "Friggin'.", 'Way.'])))
...which prints:
typing.Annotated[collections.abc.MutableSequence[str], IsInstance[WeirdoCustomList]]
"What's so hot about that?", you may now be thinking. Allow me to now pontificate boringly.
WeirdoCustomList isn't subscriptable. It's not a type hint factory. Moreover, despite being a mutable sequence, WeirdoCustomList doesn't actually subclass the standard collections.abc.MutableSequence protocol. Yet, BeartypeAI™ correctly detected that this particular weirdo custom list is a mutable sequence of strings. How? It's best not to ask weirdo custom list these questions. :rofl:
<sup>wake up BeartypeAI™ when those type hints start making sense</sup>
Callable[...] Type Hints: Gods, They Suck.Annotating callables (especially callbacks) with PEP-compliant Callable[...] type hints is basically impossible. Personally, I've never gotten a single Callable[...] type hint to work right. They never match the callables they're supposed to when I write them myself. mypy and pyright always vomit all over themselves and then me. I mostly just give up now and use the unsubscripted collections.abc.Callable abstract base class instead of full-blown Callable[...] type hints...
...until now. BeartypeAI™ knows literally everything there is to know about annotating callables. What doesn't BeartypeAI™ know? Well, friends:
BeartypeAI™ knows that a lambda function accepting no parameters is annotated as...
>>> infer_hint(lambda: "No. Friggin'. Way.")
collections.abc.Callable[[], object] # <-- woah
BeartypeAI™ knows that a lambda function accepting multiple parameters is annotated as...
>>> infer_hint(lambda you, will, believe: "@beartype, I am your code father.")
collections.abc.Callable[[object, object, object], object] # <-- i don't know what's happening here, but i like it
BeartypeAI™ knows that a normal function accepting two mandatory annotated parameters and one optional annotated parameter is "best" annotated with a PEP 612-compliant typing.Concatenate[...] subscription as...
>>> def i_am_tired(this: float, so: int, boring: str = "y u so boring, @beartype!?"): ...
>>> infer_hint(i_am_tired)
collections.abc.Callable[typing.Concatenate[float, int, ...], object] # <-- don't ask, just accept.
BeartypeAI™ knows that a decorator wrapper function accepting a PEP 612-compliant parameter specification is annotated as...
>>> from typing import ParamSpec
>>> P = ParamSpec('P')
>>> def so_param_so_spec(*args: P.args, **kwargs: P.kwargs): ...
>>> infer_hint(so_param_so_spec)
collections.abc.Callable[~P, object] # <-- yer frickin' blowin' mah mind here, yo
BeartypeAI™ knows that a decorator wrapper function accepting two mandatory annotated parameters followed by a PEP 612-compliant parameter specification is annotated with a PEP 612-compliant typing.Concatenate[...] subscription as...
>>> from typing import ParamSpec
>>> P = ParamSpec('P')
>>> def more_param_more_spec(
... go_crazy: int,
... dont_mind_if_i_do: str,
... *args: P.args,
... **kwargs: P.kwargs
... ): ...
>>> infer_hint(more_param_more_spec)
collections.abc.Callable[typing.Concatenate[int, str, ~P], object] # <-- pretty sure the universe just exploded
What I'm trying to say here is that BeartypeAI™ knows all and sees all and doesn't like it what it sees, but is still doing it's best for everybody. It knows more than me. It probably knows more than even you, even though you know everything. That's how much BeartypeAI™ knows.
<sup>BeartypeAI™ takes the high road when it comes to Callable[...] type hints</sup>
Tensor type hints really suck. So your team wants to annotate NumPy, JAX, PyTorch, or TensorFlow arrays, huh? That's a perfectly reasonable request. Too bad, though. Because tensor type hints suck.
Tensor type hints suck so bad you have to use third-party packages like jaxtyping just to make them work, despite the fact that both NumPy and JAX ship type hint-centric subpackages like numpy.typing and jax.typing that are supposed to make tensor type hints "just work." Of course, tensor type hints don't "just work." They don't even work...
...until now. BeartypeAI™ knows literally everything there is to know about annotating tensor type hints. Actually, that's a lie. I really wanted BeartypeAI™ to know literally everything there is to know about annotating tensor type hints in time for @beartype 0.19.0rc1. Sadly, I played video games instead. I only got around to implementing BeartypeAI™ support for inferring NumPy tensor type hints.
Still, NumPy is better than nothing. One out of four ain't bad. Right? ...anybody? :face_exhaling:
# Define the greatest NumPy array that has ever existed.
>>> from numpy import asarray
>>> best_array_is_best = asarray((1, 0, 3, 5, 2, 6, 4, 9, 2, 3, 8, 4, 1, 3, 7, 7, 5, 0,))
# Create a type hint validating that array, @beartype! Look. Just do it.
>>> from beartype.door import infer_hint
>>> infer_hint(best_array_is_best)
typing.Annotated[numpy.NDArray[int], beartype.vale.IsAttr['ndim', beartype.vale.IsEqual[1]]] # <-- wtf, @beartype
And... that's the type hint. That type hint requires no third-party dependencies. It's all BeartypeAI™, all one-liner. Nobody's writing that sort of gruelling bracket hell on their own. Not even @leycec. Just let somebody else do your suffering for you. That somebody is BeartypeAI™. Who knew?
<sup>your codebase grips its hat as BeartypeAI™ boldly shows off for no reason</sup>
infer_hint() Time Complexity: All Roads Lead to O(1)infer_hint() is the first @beartype API to respect the long-standing BeartypeConf(strategy=BeartypeStrategy.O*)configuration option. Previously, *all* @beartype APIs defaulted toO(1)` constant-time behaviour by randomly sampling container items for improved scalability. In the future, all @beartype APIs will allow you to customize this behaviour by specifying alternate iteration strategies like:
O(n) linear-time behaviour, in which @beartype exhaustively examines all possible container items with recursion.O(log n) logarithmic-time behaviour, in which @beartype recursively examines only a logarithmic subset of all possible container items – a scalable compromise between non-deterministic O(1) immediacy and deterministic O(n) lethargy.Now, infer_hint() is the first @beartype API to fully support two of those three strategies. Witness as history unfolds with a discomfiting "plop!":
infer_hint(obj) is equivalent to infer_hint(obj, conf=BeartypeConf(strategy=BeartypeStrategy.On))). Under the O(n) strategy, infer_hint() exhaustively examines all possible container items with recursion. To infer authoritative type hints from interactive REPLs and Jupyter Notebooks, infer_hint() differs from the remainder of the @beartype codebase by defaulting to O(n)-style linear-time iteration. This is generally what most users "probably" want when inferring type hints. Since you are reading this, you are not one of those users.infer_hint(obj, conf=BeartypeConf(strategy=BeartypeStrategy.O1))). Under the O(1) strategy, infer_hint() pseudo-randomly examines only a single container item at each nesting level. This is generally what algorithms like structural similarity <sup>see below</sup> and multiple dispatch <sup>more seeing below</sup> want. To activate the Hyperlight Drive, these use cases want to explicitly pass a conf enabling the O1 strategy.BeartypeStrategy.O1: punch it, bald man!
<sup>@leycec punches it with fear in his heart</sup>
infer_hint() Use Cases: Where We Pontificate Both Laconically and LoquaciouslyWhat do those words even mean? Doesn't matter. Thankfully, what does matter is that type hint inference has real-world use cases that far exceed just "write my type hints for me, cause i h8 type hints m8. fr!" Just get a gander of these algorithmic goodies:
O(1) structural similarity comparison – faster even than ==-based equality comparison between arbitrary objects, which has worst-case O(n) linear-time complexity and thus scales poorly. Hyper-fast object comparison is what we sayin'.O(1) and worst-case O(k) multiple-dispatch for k the number of callables being dispatched to – probably the fastest multiple-dispatch algorithm in any language. Hyper-fast dispatch is what we still sayin'.Let's plumb these depths like Mario on a Piranha plant pipe bender.
<sup>@beartype smokes two bug-filled joints. then, @beartype smokes two more.</sup>
In the beginning, there was:
# The "is" operator. Test whether two objects are literally identical.
>>> "I like big bugs and I cannot lie." is "I like big bugs and I cannot lie."
True
# The "==" operator. Test whether two objects are semantically identical.
>>> ['Other', 'devbros', 'may', 'deny',] == ['Other', 'devbros', 'may', 'deny',]
True
But what if you want to test whether two objects are merely structurally similar (i.e., have a similar internal structure but are neither literally nor semantically identical)? Without BeartypeAI™, you can't do that. But you have BeartypeAI™. You no longer have to accept the mouldy table scraps that the standard Python library has left you.
Structural similarity compares the large-scale "shape" of two objects without regard for the small-scale minutiae (like the exact items) in those objects. Structural similarity thus combines:
is operator (like O(1) time complexity when calling infer_hint(obj, conf=BeartypeConf(strategy=BeartypeStrategy.On)))) with...== operator (like actually computing meaningful work) with...Tensors offer a useful way to understand structural similarity: "Do two tensors have the same dtype (i.e., type of all items in a tensor) and ndim (i.e., dimensionality)? If yay, those two tensors are structurally similar; if nay, those two tensors are structurally dissimilar."
There are two different kinds of structural similarity, broadly speaking:
>>> from beartype.door import infer_hint, is_bearable # <-- boring stuff
# @beartype builds excitement builds. Declare data structures for great glory of your code.
>>> awesome_data_structure = [{"hoh, boy": int, "lol, golgo 13": [lambda: None]}, 0xFAAAAAACE]
>>> baleful_data_structure = [0xDEAFDEFF, {"nopleaseno": [lambda: False], "NOOOO!": object}]
# Describe the internal structure of your final masterpiece.
>>> awesome_hint = infer_hint(awesome_data_structure)
list[int | dict[str, list[collections.abc.Callable[[], object]] | type[int]]] # <-- ok
>>> baleful_hint = infer_hint(baleful_data_structure)
list[int | dict[str, type[object] | list[collections.abc.Callable[[], object]]]] # <-- whateva you say, bear
# Do these two objects have the exact same internal structure?
>>> awesome_hint == baleful_hint
False # <----- no dice, huh? *sigh*
awesome_hint contains a dictionary mapping to integers, baleful_hint contains a dictionary mapping to merely objects. You are now thinking: "Integers are objects, you doltish man. Shouldn't we be able to ignore these awkward trivialities?" I object to being called a dolt while admitting you make a point. Make things vaguer by harnessing the perfidious power of beartype.door.infer_hint() + beartype.door.is_bearable(). Arise, substructural similarity! A new darkness!>>> from beartype.door import infer_hint, is_bearable # <-- boring stuff
# Excitement builds. Declare data structures for great glory of your code.
>>> awesome_data_structure = [{"uhh...": int, "wat!?!": [lambda: None]}, 0xFEEEEEEED]
>>> baleful_data_structure = [0xBABEEEE, {"ohgod": [lambda: True], "NOOOO!": object}]
# Describe the internal structure of your great glory.
>>> infer_hint(awesome_data_structure)
list[int | dict[str, list[collections.abc.Callable[[], object]] | type[int]]] # <-- ok
>>> infer_hint(baleful_data_structure)
list[int | dict[str, type[object] | list[collections.abc.Callable[[], object]]]] # <-- i don't know. sure, i guess?
# Do these two objects have a similar internal structure?
>>> is_bearable(baleful_data_structure, infer_hint(awesome_data_structure))
True # <----- WTF-F-F-F-F-
Structural similarity cheatsheet, because the one-liner is a harsh mistress:
infer_hint(obj_1) == infer_hint(obj_2).is_bearable(obj_1, infer_hint(obj_2)).Structural similarity: when you care about what your objects care about.
<sup>say goodbye to expensive comparisons that never really liked you anyway</sup>
"Dispatch" is a common decision problem in... well, basically any modern language that matters. So, not C. <sup>i have no regrets for igniting this flame war</sup>
Everyone's familiar with single-dispatch polymorphism, whereby an object-oriented language dynamically routes a call of an object's method to that object's "deepest" subclass overriding that method. In Python, we call this the method-resolution order (MRO) of an object. It's quite boring and pedantic stuff, really. I personally wouldn't click any of those links – especially not on the weekend.
But what if you want to perform single-dispatch outside of a class hierarchy that you directly control? Moreover, what if want to single-dispatch on arbitrary type hints deeply describing the internal structures of objects? Classes are superficial; they fail to fully convey the types of items contained in instances of those classes, which is why we do this type hint thing.
Moreover, what if we want to perform multiple-dispatch, whereby the callable that is dynamically routed to (i.e., called) depends not simply on the type of a single object but an arbitrary number of objects? This is the dynamical Hell we now find ourselves in.
Interestingly, it turns out that combining the beartype.door.infer_hint() + beartype.door.is_bearable() functions trivially yields highly efficient O(1) algorithms that transparently implement both single- and multiple-dispatch. First, the full-throttle single dispatch algorithm:
from beartype import BeartypeConf, BeartypeStrategy, beartype
from beartype.door import infer_hint, is_bearable
from collections.abc import Callable
_CONF_STRATEGY_O1 = BeartypeConf(strategy=BeartypeStrategy.O1)
'''
Beartype configuration enabling :math:`O(1)` constant-time random sampling.
'''
@beartype
def single_dispatch(obj: object, dispatcher: dict[object, Callable]) -> Callable:
'''
Callable suitable for dispatching the passed object from a type hint of the
passed dispatch dictionary.
Parameters
----------
obj : object
Object to be dispatched.
dispatcher : dict[object, Callable]
**Dispatch dictionary** (i.e., dictionary mapping from various type hints
to corresponding callables dispatching the passed object when that object
is validated by those type hints).
'''
# O(1) type hint inference, I choose you!
obj_hint = infer_hint(obj, conf=_CONF_STRATEGY_O1)
# Go for the O(1) short-circuit, @beartype. Do it.
dispatch_callable = dispatcher.get(obj_hint)
if dispatch_callable and is_bearable(obj, obj_hint):
return dispatch_callable
# Oh, noes! Disaster. Fallback to the O(k) iteration. Pretend this is okay.
for dispatch_hint, dispatch_callable in dispatcher.items():
if is_bearable(obj, obj_hint):
# Inject this inferred type hint and corresponding callable back into
# the dispatch dictionary, reducing the next call of this function
# passed a similar object to the O(1) short-circuit above. This
# guarantees amortized O(1) time complexity. </high_fives_all_around>
dispatcher[obj_hint] = dispatch_callable
return dispatch_callable
raise DispatchException(f'Passed object {repr(obj)} sucks. Blowing everything up!')
This exhibits time complexity:
O(1). <sup>oh by gods</sup>O(1). <sup>the gods glare with envy</sup>O(k) for k callables being dispatched to. <sup>the gods smugly look down and snicker</sup>Generally speaking, we expect k to be small in the average case – like, k < 10 small. So this is basically O(1) single-dispatch in even the non-amortized worst case.
Totally realistic and compelling usage resembles something like:
# User-defined callables to be dispatched to. Excitement builds.
def join_list_of_strs(lst: list[str]) -> str:
return ''.join(lst)
def join_list_of_bytes(lst: list[bytes]) -> bytes:
return b''.join(lst)
# User-defined object to be dispatched on. Excitement peaks.
list_of_things = [b'This. ', b'String. ', b'Bytes.']
# User-defined callable suitable for this object. Excitement subsides.
join_list_of_things = single_dispatch(list_of_things, dispatcher={
list[str]: join_list_of_strs,
list[bytes]: join_list_of_bytes,
})
# Pass this object to this callable. Excitement is in the gutter now.
assert join_list_of_things(list_of_things) == b'This. String. Bytes.'
That's probably the fastest possible single-dispatch algorithm in any language. But here's where the bullet train really goes off the rails...
<sup>@beartype flies foolishly close to the fathomless void so you don't have to</sup>
The single-dispatch algorithm trivially generalizes to multiple-dispatch as well. How? With cleverness, grit, and twin handlebar moustaches. :man: :man: <sup>← gritty moustauche twins</sup>
Let's reduce the multiple-dispatch case (of dispatching over multiple objects) to the single-dispatch case (of dispatching on a single object) by concatenating those multiple objects into a single object. Specifically, let's encapsulate those multiple objects into a tuple. Tuples are highly space- and time-efficient in Python. More importantly, tuples whose items are hashable are themselves hashable. By subscripting fixed-length tuple[...] types by the multiple type hints (almost all of which are hashable) to be dispatched across, we can actually leverage the almost exact same algorithm as above to perform O(1) multiple dispatch:
from beartype import BeartypeConf, BeartypeStrategy, beartype
from beartype.door import infer_hint, is_bearable
from collections.abc import Callable, Collection
_CONF_STRATEGY_O1 = BeartypeConf(strategy=BeartypeStrategy.O1)
'''
Beartype configuration enabling :math:`O(1)` constant-time random sampling.
'''
@beartype
def multiple_dispatch(
*args: object, dispatcher: dict[object, Callable]) -> Callable:
'''
Callable suitable for dispatching all objects in the passed collection from a
type hint of the passed dispatch dictionary.
Parameters
----------
*args : object
Tuple of all objects to be dispatched.
dispatcher : dict[object, Callable]
**Dispatch dictionary** (i.e., dictionary mapping from various type hints
to corresponding callables dispatching the passed objects when those objects
are validated by those type hints).
'''
# O(1) type hint inference, I choose you!
obj_hint = infer_hint(args, conf=_CONF_STRATEGY_O1)
# Go for the O(1) short-circuit, @beartype. Do it.
dispatch_callable = dispatcher.get(obj_hint)
if dispatch_callable and is_bearable(args, obj_hint):
return dispatch_callable
# Oh, noes! Disaster. Fallback to the O(k) iteration. Pretend this is okay.
for dispatch_hint, dispatch_callable in dispatcher.items():
if is_bearable(args, obj_hint):
# Inject this inferred type hint and corresponding callable back into
# the dispatch dictionary, reducing the next call of this function
# passed a similar object to the O(1) short-circuit above. This
# guarantees amortized O(1) time complexity. </high_fives_all_around>
dispatcher[obj_hint] = dispatch_callable
return dispatch_callable
raise DispatchException(f'Passed object {repr(obj)} sucks. Blowing everything up!')
That's... literally the exact same function. The signature just accepts variadic positional arguments *args rather than a single obj. Whatevah!
Crucially, this is still amortized worst-case O(1) and non-amortized worst-case O(k) multiple-dispatch for k the number of callables being dispatched. In other words, we have a cardinality-invariant dispatch algorithm. The time complexity of this algorithm is unconditionally O(k) regardless of the number of objects being dispatched over or the size of those objects. Since we generally expect k to be small, this is still basically O(1) multiple-dispatch. wuuuuuuuuuut
Totally realistic and compelling usage intensifies holistically:
# User-defined callables to be dispatched to. Excitement builds.
def join_list_of_strs_plus_str(lst: list[str], text: str) -> str:
return ''.join(lst) + text
def join_list_of_bytes_plus_bytes(lst: list[bytes], text: bytes) -> bytes:
return b''.join(lst) + text
# User-defined objects to be dispatched on. Excitement peaks.
list_of_things = [b'This. ', b'String. ', b'Still. ',]
plus_thing = b'Bytes.'
# Tuple of all user-defined objects to be dispatched over.
list_of_things_plus_thing = (list_of_things, plus_thing)
# User-defined callable suitable for these objects. Excitement subsides.
join_list_of_things_plus_thing = multiple_dispatch(*list_of_things_plus_thing, dispatcher={
tuple[list[str], str]: join_list_of_strs_plus_str,
tuple[list[bytes], bytes]: join_list_of_bytes_plus_bytes,
})
# Pass these objects to this callable. Excitement is in the gutter now.
assert join_list_of_things_plus_thing(*list_of_things_plus_thing) == b'This. String. Still. Bytes.'
That's definitely the fastest possible multiple-dispatch algorithm in any language. Can't do better than O(1). Suck it, Julia. Suck it.
I've tested that rickety jerry-rigged shadow madness. Against all odds... it somehow works. No idea how, honestly. Probably falls down in edge cases, honestly. But at least for one fleeting moment in the rain, we had a dream of something beautiful. :rofl:
<sup>O(1) multiple dispatch: the skull means it wants to help you</sup>
**kwargs: The Type-checking Chickens Come Home to RoostA few bicycle trips ago, my wife asked me a real eye-opener as the stinging sweat trickled down:
Why does "his chickens came home to roost" always mean that something bad just happened? Isn't it a good thing when the chickens come home to roost? Isn't that what chickens are supposed to do at night? Roost?
Me:
I see that you too have autism.
Seriously. Metaphors, folks. What good are they for if they make less sense than cats wearing pizza hats? Which leads us straight to...
Variadic keyword arguments. All this time, it was reasonable to believe that @beartype was type-checking annotated variadic keyword arguments like def func_in_a_funk(**kwargs: int). In actuality, @beartype was type-checking nothing there. Annotated variadic keyword arguments were silently ignored. Our flimsy reasons for doing nothing were fivefold:
The last reason is a good reason. The rest are bad reasons. Therefore, @beartype now type-checks annotated variadic keyword arguments as standardized by PEP 484 a decade ago.
The syntax is a bit odd, though. Although boring, this is worth belabouring. Python usually wants you to explicitly spell everything out. "Explicit is better than implicit" – except when it's not, apparently. All variadic keyword arguments are dictionaries mapping from strings (i.e., excess parameter names passed by keyword) to arbitrary objects (i.e., the values of those parameters). So far, so boring.
Since all variadic keyword arguments necessarily satisfy the type hint dict[str, object], however, Python interprets the type hint annotating a variadic keyword argument as the child value type hint of that dictionary. Thus, def oh_boy(**kwargs: float) is semantically equivalent to def oh_boy(kwargs: dict[str, float]) from the perspective of the body of oh_boy(). So far, still boring... albeit kinda weird and meandering now.
Above, I self-importantly wrote that "The types of the values of excess keyword arguments vary by keyword." The real-life embodiment of this is:
def fugly_muffin(**kwargs) -> int:
return kwargs['hear_nuffin'] + len(kwargs['see_nuffin'])
assert ugly_muffin(hear_nuffin=0xDEAF, see_nuffin='NOPE.') == 57012
Above, the first excess keyword parameter hear_nuffin has type int while the second excess keyword parameter see_nuffin has type str. How do you type this madness as a single type hint when the types vary by keyword? Simple:
The Beartype-Friendly Way, which is also the awful way. This approach has the benefit of being supported by @beartype, but the drawback of sucking. You ambiguously type **kwargs as the union of the types of the values of all excess keyword arguments: e.g.,
# This is trash. What you goin' do?
def fugly_muffin(**kwargs: int | str) -> int:
return kwargs['hear_nuffin'] + len(kwargs['see_nuffin'])
The PEP 692 Way, which is honestly also kinda awful. This has the benefit of being unambiguous (unlike the "Beartype-Friendly Way" above), but the multiple drawbacks of not currently being supported by @beartype, requiring Python ≥ 3.12, and expanding into 500 lines of sad-faced boilerplate that will break your will to sling code on Friday nights. Under PEP 692, you type **kwargs as the typing.Unpack of a typing.TypedDict subclass that you define just to unambiguously constrain the types of the values of all excess keyword arguments: e.g.,
# This is still trash -- merely a different and larger kind of trash.
from typing import TypedDict, Unpack
class _GodsThisIsTrashy(TypedDict):
'''
You didn' see nuffin' except 500 lines of boilerplate that burn the eyes.
'''
hear_nuffin: int
see_nuffin: str
def fugly_muffin(**kwargs: _GodsThisIsTrashy) -> int:
'''
Still trashy after all these years.
'''
return kwargs['hear_nuffin'] + len(kwargs['see_nuffin'])
Even if @beartype supports PEP 692 by the time you read this, <sup>Spoiler from the sad future: ...it still doesn't!?</sup> I'd still personally opt for the @beartype-friendly def fugly_muffin(**kwargs: int | str): approach. Sure, it's ambiguous. But it's also a trivial 9 characters rather than 500 lines of sad-faced boilerplate. Consider the number of callables that accept **kwargs in your codebase. Are you really gonna define one unique TypedDict subclass just to unambiguously annotate each **kwargs parameter? Really? Some of us might think we are. But then we try and fall down clutching our rib cages. The finger-breaking reality of that much boilerplate has broken greater devs than us before.
I scoff into my "Revenge of the Nerds"-era pocket protector. Annotating variadic keyword arguments may still suck after all these years – but at least @beartype now supports the slightly less sucktastic way.
<sup>five out of ten men who are pigs support this feature. do you?</sup>
Let's create a fake PEP and pretend it exists. In other words, this subsection is of no value to anyone whatsoever. Still, unhinged dreams exist for a reason. If I was a CPython typing dev, this is the Mirror World PEP 692 that I personally would have written to trivialize **kwargs type hints:
from typing import Unpack
def fugly_muffin(**kwargs: Unpack['hear_nuffin': int, 'see_nuffin': str]) -> int:
return kwargs['hear_nuffin'] + len(kwargs['see_nuffin'])
Trivial. Right? Just subscript typing.Unpack[...] with dictionary-like key-value pairs of the names and types of all excess keyword arguments accepted by that callable. This is already valid Python syntax as shown above. No changes to the CPython PEG (Parser Expression Grammar) or parser are required. This syntax promotes trivial, readable, maintainable, debuggable one-line type hints for **kwargs. No extraneous 500-line TypeDef subclasses or whatevah boilerplate are required.
Moreover, this same syntax easily generalizes to Callable[...] type hints. Currently, Callable[...] type hints fail to support keyword arguments; they only support positional-only parameters. Since nobody uses positional-only arguments, Callable[...] type hints are basically useless as defined. Instead, Callable[...] type hints could be readily extended using the exact same syntactic mechanism to support both keyword and keyword-only arguments: e.g.,
from collections.abc import Callable
# This should, like, totally be the way you annotate callbacks in Python and stuff.
def call_back(callback: Callable[['trust_me_bro': int, 'grifter': str], int]) -> int:
return callback(trust_me_bro=42, grifter='y u so grifty, Grifty McGrift?')
Dictionary-like syntax should totally be the standard way to type keyword parameters. We know I mean standardization business, because I just used the word "totally."
<sup>man-pig ponders the existential nature of bad standards, as nobody cares</sup>
beartype_all(): It Actually Works Now, KindaAh, yes. The venerable beartype.claw.beartype_all() import hook. Anybody remember that thing? Me neither. Nobody uses that thing, because that thing blows up whenever you look at it. Let's back up.
beartype_all() unconditionally type-checks literally everything. Whereas beartype_this_package() only type-checks your package, beartype_all() type-checks both your package and everybody else's packages too. <sup>Fake footnote: Technically, this includes even the standard CPython library. Pragmatically, the standard CPython library contains no type hints whatsoever. Why? Because CPython devs hate runtime typing. This fake footnote means nothing. I wasted my time writing this. You wasted your time reading this. We cry tears in the rain together.</sup>
It's the "everybody else's packages too" part that is the problem there. Although you expect your package to be type-checked with @beartype, nobody else does. Nobody expects their package to be type-checked with @beartype without their permission or knowledge – at least, not until you open 317 pending issues on their issue tracker enumerating every shocking yet mundane "error" in their package when type-checked with @beartype. This is why beartype_all() fails you when you need it most. You can't control other people's intransigence towards the Bear... until now.
Introducing the new BeartypeConf(claw_skip_package_names: Collection[str] = ()) configuration option! claw_skip_package_names is a package name blacklist (e.g., ban, deny, ignore, or omit list of the names of all packages and modules to be excluded from consideration), enabling you to selectively ignore one or more problematic third-party packages when type-checking the entire Universe via beartype_all(). The Universe just got a little smaller and a lot smarter, folks.
Because claw_skip_package_names is sane:
list, tuple, set, whatevahs).'bad_apple').'lovely_cat.ugly_dog').Because reality is even more disappointing than public education prepared us for, the claw_skip_package_names "option" is basically mandatory. It's not optional despite being called an option. Whenever you call beartype_all(), you also need to pass claw_skip_package_names: e.g.,
from beartype import BeartypeConf
from beartype.claw import beartype_all
# Beartype everything except sucky packages that hate everything good in the world.
beartype_all(conf=BeartypeConf(claw_skip_package_names=(
'some_sucky_package',
'another_package_hates_you',
'this_package_is_great.this_submodule_is_trash',
)))
claw_skip_package_names: because the Universe is kinda like in the Aliens franchise.
<sup>when you fly with @beartype, you fly with a man who is a pig</sup>
beartype_all() + pytest-beartype: They Were Meant for Each Otherpytest-beartype plugin users are now thoughtfully chewing their upper lips and thinking:
What about us!? We deserve better, too. Neglect us and we'll burn this issue tracker down.
You do you. That's why pytest-beartype maintainer (and all-around Python-Zig tooling God) @tusharsadhwani has already implemented support for command-line equivalents of both the beartype_all() import hook and the claw_skip_package_names option. In short, just:
pytest --beartype-packages='*' --beartype-skip-packages='awful_package, horrible.submodule'
Let's unpack this. CLI stuff is always so crufty, isn't it? Passing:
--beartype-packages='*' instructs pytest-beartype to internally call the universal beartype_all() import hook rather than the local beartype_packages() import hook. Good.--beartype-skip-packages blacklists those packages and modules from consideration. Good.--beartype-skip-packages: because not all heroes write one-liners.
<sup>sick burn, pig-man. but what does this have to do with @beartype? the answer may shock somebody.</sup>
O(1) Type-checking@beartype 0.19.0 deeply type-checks a ton of fun containers I've loosely dubbed reiterables.
A reiterable is a collection satisfying the collections.abc.Collection protocol with guaranteed O(1) read-only access to only the first collection item. Reiterables include sets, frozen sets, dictionary views, deques (i.e., double-ended queues), and all other containers matched by one or more of the following PEP 484- or 585-compliant type hints:
frozenset[...].set[...].collections.ChainMap[...].collections.Counter[...].collections.deque[...].collections.abc.Collection[...].collections.abc.ItemsView[...].collections.abc.KeysView[...].collections.abc.MutableSet[...].collections.abc.Set[...].collections.abc.ValuesView[...].typing.AbstractSet[...].typing.ChainMap[...].typing.Collection[...].typing.Counter[...].typing.Deque[...].typing.FrozenSet[...].typing.ItemsView[...].typing.KeysView[...].typing.MutableSet[...].typing.Set[...].typing.ValuesView[...].@beartype now deeply type-checks almost all of the core PEP 484 and 585 standards, resolving feature request #167 kindly submitted by the perennial brilliant @langfield (...how I miss that awesome guy!) several lifetimes ago back when I was probably a wandering vagabond Buddhist monk with a bad attitude, a begging bowl the size of my emaciated torso, and an honestly pretty cool straw hat that glinted dangerously in the firelight.
There's still a bit of low-hanging fruit dangling its juicy skin here and there – but not much. The biggest offenders that have yet to be deeply type-checked are:
Iterable[...] type hints. Not hard, so I claim. Just needs a bit of spit and polish, so I claim. I'm claiming lots of things without hard evidence here.
Callable type hints (e.g., collections.abc.Callable[...], typing.Callable[...]). Thankfully, BeartypeAI™ now provides a trivial O(1) one-liner for deeply type-checking any callable type hint hint against any arbitrary callable func:
def is_func_bearable(func: Callable, hint: object) -> bool:
return is_subhint(infer_hint(func), hint) # <-- lolbro
Type variables (e.g., typing.TypeVar('T'). Still no idea how to dynamically generate efficient code type-checking type variables, honestly. It's feasible, but let's avoid thinking about this until there's absolutely nothing left to do. :sweat_smile:
...how is to possible that so much and yet so little has changed? Please manage our time better or we're never gonna cross that finish line, GitHub. @leycec assumes no responsibility for just playing video games for a year.
@beartype: It's actually starting to do stuff, now.
<sup>if i'm reading these schematics right, @beartype actually does stuff now</sup>
@beartype's love for PEP 612 – Parameter Specification Variables, PEPs646 – Variadic Generics, and PEP 692 – Using TypedDict for more precise **kwargs typing may be a tepid pool of mucky brackish water you can barely dip your toes into – but at least @beartype 0.19.0 tried, daggumit.
@beartype 0.19.0 now supports you in your aspirations to obfuscate decorator closures beyond the dark horizon of MIT Python obfuscation competitions by silently ignoring those aspirations:
# Guido himself defined a decorator so complex it "logs to a database"
# while exploding @beartype with soul-sucking parameter specifications.
from typing import Awaitable, Callable, ParamSpec, TypeVar
P = ParamSpec("P")
R = TypeVar("R")
def add_logging(f: Callable[P, R]) -> Callable[P, Awaitable[R]]:
async def inner(*args: P.args, **kwargs: P.kwargs) -> R:
await log_to_database()
return f(*args, **kwargs)
return inner
@beartype doesn't pretend to understand what typing.ParamSpec('P').kwargs means, but @beartype doesn't have to. @beartype is here to crush bugs and play video games... and @beartype is all outta video games.
<sup>that one unforgettable moment when @beartype 0.19.0 reveals its true nature</sup>
TypedDict Is Useful for Something@beartype 0.19.0 now supports you in your aspirations to precisely type-check **kwargs by silently ignoring those aspirations:
from beartype import beartype
from typing import TypedDict, Unpack
class Kwargs(TypedDict):
this_kwarg_must_be_a_string: str
this_kwarg_must_be_a_complex_number_just_kidding_its_actually_an_integer: int
@beartype
def function_accepts_two_kwargs(**kwargs: Unpack[Kwargs]) -> None: ...
That's better than @beartype used to do (which was blow chunks everywhere). We don't deeply type-check this yet, but we will. Would @leycec lie!? :sweat:
<sup>newer and sleaker @beartype does a surprise fly-by over your codebase. hats are almost lost.</sup>
It's all tuples all the way down with PEP 646.
@beartype 0.19.0 now supports you in your aspirations to precisely type-check... actually, I really have no idea. But that's okay, because neither does @beartype 0.19.0. What is PEP 646 besides really confusing? Couldn't tell ya. All I know is that @beartype now silently ignores PEP 646-compliant type variable tuples (i.e., typing.TypeVarTuple objects):
from beartype import beartype
from typing import TypeVar, TypeVarTuple
DType = TypeVar('DType')
Shape = TypeVarTuple('Shape')
@beartype
class Array(Generic[DType, *Shape]):
def __abs__(self) -> Array[DType, *Shape]: ...
def __add__(self, other: Array[DType, *Shape]) -> Array[DType, *Shape]: ...
I kinda get it, but I kinda don't. Since @beartype 0.19.0 doesn't get it any more than I do, @beartype doesn't deeply type-check TypeVarTuple objects yet. Will it ever? No idea. Let's pretend:
"Yes! Absolutely! All your dreams will be realized by... @beartype 42.42.42!?"
@beartype doesn't even deeply type-check TypeVar objects yet – which is the slightly lower-hanging fruit here. Oh, when will free time materialize for @leycec? What has @beartype done to deserve this punishing development schedule? I fear for your immortal git log, @beartype. :fearful:
<sup>@beartype 42.42.42 chortles as it contemplates the darkness of the past</sup>
@beartype 0.19.0 officially supports the standard multiprocessing API for fork-based distributed workloads. All beartype exceptions (i.e., exception subclasses published by the beartype.roar subpackage) now support pickling and unpickling via the standard pickle module, which then suffices to support the standard multiprocessing package, which shockingly leverages pickle rather than dill in 2024.
@beartype 0.19.0: "Why is pickle still even a thing!?"
<sup>You're stupid, multiprocessing. I hate that in an API.</sup>
@beartype 0.19.0 goes hard on integration with external decorators published by third-party packages that previously hated @beartype. This includes popular Just-in-Time (JIT) decorators for machine learning (ML) like:
@equinox.filter_jit.@jax.jit.@numba.njit.@beartype should now support almost everybody else's decorators. In fact, @beartype now generically supports all pseudo-callable wrapper objects (i.e., objects defining both the __call__() and __wrapped__ dunder attributes).
The @beartype decorator should also now be context-free. You may now chain (i.e., list) @beartype above or below most third-party decorators. Since beartype.claw import hooks (like beartype_this_package() and beartype_package()) inject @beartype above all other decorators, beartype.claw import hooks now transparently support all other decorators... probably. :grimacing:
If you previously blacklisted @beartype from type-checking callables decorated by any of the above with @typing.no_type_check, let us give thanks as you remove @typing.no_type_check everywhere.
Examples or it only happened in the DMT hyperplane:
from beartype import beartype
from jax import (
jit,
numpy as jax_numpy,
)
from jaxtyping import (
Array,
Float,
)
@beartype # <-- *GOOD*. @beartype goes last! patiently suffer in silence, @beartype.
@jit # <-- *GOOD*. @jax.jit goes first! yoink.
def what_would_chat_gpt_do(
probably_hallucinate_everything: Float[Array, '']) -> Float[Array, '']:
# One-liner: "Do what I say, not what I code."
return probably_hallucinate_everything + 1
assert what_would_chat_gpt_do(jax_numpy.array(1.0)) == jax_numpy.array(2.0)
what_would_chat_gpt_do('If this is a JAX array, we all have serious problems.')
...which raises the expected type-checking violation:
Traceback (most recent call last):
File "/home/leycec/tmp/mopy.py", line 22, in <module>
what_would_chat_gpt_do('If this is a JAX array, we all have serious problems.')
File "<@beartype(PjitFunction.__call__) at 0x7fd9afc96140>", line 29, in __call__
beartype.roar.BeartypeCallHintParamViolation: Object
PjitFunction.__call__() parameter probably_hallucinate_everything='If
this is a JAX array, we all have serious problems.' violates type hint
<class 'jaxtyping.Float[Array, '']'>, as str 'If this is a JAX array, we
all have serious problems.' not instance of <protocol
"jaxtyping.Float[Array, '']">.
The perspicacious user may now be thinking:
"WAIT. What is a
PjitFunction.__call__()? That's ambiguous and means less than my cat licking itself. Your type-checking violation message sucks, huh?"
You're not wrong. But we're tired. At least @beartype works now for various definitions of "works." If you just hit this ambiguous type-checking violation message in your workflow and want @beartype to justifiably do something about it, bang on our issue tracker until the cats start squalling and biting @leycec in the face. Works every time.
@beartype 0.19.0: we broke our sanity for your security.
<sup>@beartype 0.19.0: it's been a long journey, fam.</sup>
@beartype 0.19.0 officially supports Python 3.13, the first official CPython release you no longer need to feel ashamed of running in public.
Python 3.13 supports an official LLVM-based Just-in-Time (JIT) compiler via the PEP 744-compliant --enable-experimental-jit compile-time option. OMMMMMMMMMMMMMMMMG..... It's happening. It's really happening. My breathing is now laboured and making awkwardly squishy noises that upset the cat.
Python 3.13 also supports no-GIL GIL-free multi-threading via the PEP 703-compliant --disable-gil compile-time option. Yes! YES! YEEEEEEESSSSS!!!! Wait. Where am I? What are these fingers on this keyboard? This must be what Xanadu is typed of.
If I worked on a proprietary Python package, I'd have money. I'd also:
python >=3.13 for production workloads as soon as CPython 3.13 lands in October.--enable-experimental-jit for development workloads.It's time to go fast. Finally, it's time to feel shameless.
<sup>OMG IZ @beartype + CPython 3.13 + --enable-experimental-jit WTF FAFO!!!</sup>
@beartype 0.18.0 broke the entire world. @leycec can now admit that to himself while clutching his Maine Coon teddy cat. If your codebase survived @beartype 0.18.0, you deserve an "I Survived @beartype 0.18.0 and All I Got Was This Lousy Badge" badge. The ill-fated @beartype 0.18.0 release cycle that nearly broke my fingers taught me many things: suffering, pain, agony, blah, blah... You know. Just the standard stuff, really.
@beartype 0.18.0 taught me that @beartype has become a lot bigger than me. Other people and people-like AI that are doing meaningful things with their lives and synthetic lives (respectively) now depend on new @beartype releases not throwing up all over everybody.
@beartype ≥ 0.19.0 intends to avoid that throw-up. Several days before releasing any new major version like 0.19.0, 0.20.0, or 0.21.0: <sup>...we see the number sequence I trust</sup>
Basically, I'm just doing standard beta releases now. That's all I had to say. Instead, I laboriously enumerated a workflow that doesn't really make sense when you squint at it. Oh, well. This too was wasted time.
The sins of the fathers must never be repeated. Never forget @beartype 0.18.0! Never forgive @leycec! Wait. Shouldn't @leycec be forgiven already at some point!? <sup><-- dat poor guy</sup>
<sup>@beartype 0.18.0: shocking behind-the-scenes tell-all reveals sordid truth of what went wrong that fateful day</sup>
In discussion thread #433, @jedie wisely asks the question we're all wondering:
There are many, many commits since last release: https://github.com/beartype/beartype/compare/v0.18.5...main
What's the release cycle? Seems it's not:
Release early, release often
isn't it?
Indeed, @jedie. It isn't. You're right about everything. I now quote myself like a narcissist. <sup>gods what am i become</sup>
For ordinary packages, "Release early, release often" is the best possible advice. For @beartype, this is the worst possible advice. Why? Because @beartype is mission-critical. When @beartype breaks, increasingly the entire Python ecosystem breaks. This includes PyTorch – which then transitively includes ChatGPT, OpenAI, Microsoft, and by extension the entirety of American late-stage capitalism. Do we grok the stakes here? The stakes somehow become a whole lot more bigly than "one bald autist has fun smashing code together in a remote Canadian cottage."
I should probably be paid to do this hyper-cuboidal tesseract we call @beartype. Imagine if all neurosurgeons were unpaid volunteers. This is hyperbole, but it's also not. @beartype is the neurosurgeon that fixes bugs during LLM training. Much like Soviets under the USSR, I pretend that I'm being paid by behaving responsibly towards the rest of humanity. "Release early, release often" is what I used to believe. Then I broke PyTorch with the ill-fated @beartype 0.18.0 release. Now, I choose wisely.
The new motto is:
Release late. Release rarely. Release safely.
On the bright side, "Release safely." is good! We can all agree. On the dark side, "Release late." and "Release rarely." are both bad. We still agree. But one out of two ain't bad. Right?
New @beartype release will probably land as follows:
0.19.0) once every six months or so.0.19.0rc0) once every month or so.This broadly parallels CPython's shift to a yearly release schedule with intermittent mid-yearly alpha and beta pre-releases. Since @beartype isn't as bigly as CPython, we can and should go faster and harder than CPython on releases – but we can't go that much faster or harder. Realistically speaking, @beartype releases will remain slower than your average open-source Python package.
Sucks, huh? I know and commiserate by blowing smoke out of gigantic nostrils on a picturesque beach.
<sup>that feeling when you're only in month 1 of an interminable 6-month release cycle</sup>
pyproject.toml: The Build System We Deserved 10 Years Ago, Today@beartype 0.19.0 now sports a sane build system. It's sporty! Somehow, we found the strength to refactor the archaic @beartype 0.18.0 toolchain from setuptools + setup.py <sup> :vomiting_face: </sup> to Hatch + pyproject.toml <sup> :clinking_glasses: </sup>. This includes support for modern packaging standards like PEP 517 and 621.
It went great, actually. Thanks for asking. I highly recommend Hatch for all projects – new and curmudgeonly alike. It's like Rust's Cargo, only Python. It actually works, unlike everything else.
Hatch: because you're too bald to fight Python anymore.
Caveat emptor:
- For most users, this doesn't matter. Celebrate.
- For package maintainers like @harens (...I'm so sorry), this means that all third-party @beartype packages in the wild now need to be manually bumped to depend on Hatch (rather than
setuptools) at build time. If your packaging ecosystem also packages Hatch, this is trivial. Else, I sympathize with your growing toothache but can do nothing for you. Emoji man sighs. :face_exhaling:
<sup>@beartype 0.19.0 now gives thanks for this build system it is about to blow up</sup>
@beartype 0.19.0 now sports a sane publishing system. It's less insane! Somehow, we found the stamina to refactor the archaic @beartype 0.18.0 release workflow from antiquated (and unsurprisingly insecure) GitHub Actions tokens :vomiting_face: to PyPI-specific "Trusted Publishers" (i.e., PyPI's modern implementation of OpenID Connect (OIDC)). :shrug:
In theory, doing so should resolve the current plethora of "Unverified details" that currently pollutes @beartype's PyPI project page. We're not unverified, PyPI! You're unverified.
In practice, doing so will almost certainly change nothing and thus have no benefit whatsoever. Indeed, doing so will probably prevent our entire release workflow from behaving as expected – further squandering scarce open-source volunteerism for no particularly good reason whatsoever.
Bureaucracy: "What is it good for when @leycec could just be playing video games about robot assassins who insist they meant well instead?"
<sup>@beartype 0.19.0: on its way to a PyPI project page near you</sup>
Announcing all the fave @beartype users from the ashes of our issue tracker:
@posita, @wesselb, @iamrecursion, @patrick-kidger, @langfield, @JelleZijlstra, @RobPasMue, @GithubCamouflaged, @kloczek, @uriyasama, @danielgafni, @JWCS, @rbroderi, @AlanCoding, @tvdboom, @crypdick, @jvesely, @komodovaran, @kaparoo, @MaximilienLC, @fleimgruber, @EtaoinWu, @alexoshin, @gabrieldemarmiesse, @James4Ever0, @NLPShenanigans, @rtbs-dev, @yurivict, @st--, @murphyk, @dosisod, @Rogdham, @alisaifee, @denisrosset, @damarro3, @ruancomelli, @jondequinor, @harshita-gupta, @jakebailey, @denballakh, @jaanli, @creatorrr, @msvensson222, @avolchek, @femtomc, @AdrienPensart, @jakelongo, @Artur-Galstyan, @ArneBachmann, @danielward27, @WeepingClown13, @rbnhd, @radomirgr, @rwiegan, @brettc, @spagdoon0411, @helderco, @paulwouters, @jamesbraza, @dcharatan, @kasium, @AdrienPensart, @sunildkumar, @peske, @mentalisttraceur, @awf, @PhilipVinc, @dcharatan, @empyrealapp, @rlkelly, @KyleKing, @skeggse, @RomainBrault, @pablovela5620, @thiswillbeyourgithub, @WeepingClown13, @JWCS, @Logan-Pageler, @knyazer, @Moosems, @frrad, @minmax, @jaanli, @jonnyhyman, @f-fuchs, @jennydaman, @denballakh, @bionicles, @taranlu-houzz, @adamtheturtle
<sup>center right: your codebase. center left: @beartype. everybody else: @beartype's competition, which doesn't of course exist.</sup>
Finally. The Big Bear has landed... *yet again!?* This better be good, @beartype 0.19.0 Release Cycle from Hell.
Finally. The Big Bear has landed... yet again!? This better be good, @beartype 0.19.0 Release Cycle from Hell.
@beartype 0.19.0 release candidate 2 – the third (and seriously better-be final) beta pre-prelease of the zombified @beartype 0.19.0 release cycle that I should have released three four months ago – lands in your lap with a sickening ploppy! sound. Tragically, typing pro @minmax discovered a last-minute critical issue blocking the release of @beartype 0.19.0 proper. With that issue now unblocked, the smelly Internet Tubes are now ready for @beartype 0.19.0 proper...
...assuming nothing else is broke. Is anything else broke? No idea. Probably. It's @beartype 0.19.0, after all. This thing will never ship. Indeed, the struggle for your codebase is like a rugby match between death robots:
pip install --upgrade --pre beartype # <-- sound of bugs panicking distantly heard
@beartype 0.19.0rc2 is brought to you by...
This release comes courtesy these proud GitHub Sponsors, without whom @leycec's cats would currently be eating grasshoppers:
Thanks so much, masters of fintech and metrology.
<sup>The Masters of Fintech and Metrology. That's who.</sup>
0.19.0rc2 Actually Do?Too tired. Next question, please. :sleeping:
In discussion thread #433, @jedie wisely asks the question we're all wondering:
There are many, many commits since last release: https://github.com/beartype/beartype/compare/v0.18.5...main
What's the release cycle? Seems it's not:
Release early, release often
isn't it?
Indeed, @jedie. It isn't. You're right about everything. I now quote myself like a narcissist. <sup>gods what am i become</sup>
For ordinary packages, "Release early, release often" is the best possible advice. For @beartype, this is the worst possible advice. Why? Because @beartype is mission-critical. When @beartype breaks, increasingly the entire Python ecosystem breaks. This includes PyTorch – which then transitively includes ChatGPT, OpenAI, Microsoft, and by extension the entirety of American late-stage capitalism. Do we grok the stakes here? The stakes somehow become a whole lot larger than "one bald autist has fun smashing code together in a remote Canadian cottage."
I should probably be paid to do this immense and insane thing we call @beartype. Imagine if all neurosurgeons were unpaid volunteers. This is hyperbole, but it's also not. @beartype is the neurosurgeon that fixes bugs during LLM training. Much like Soviets under the USSR, I just pretend that I'm being paid by behaving responsibly towards the rest of humanity. "Release early, release often" is what I used to believe. Then I broke PyTorch with the ill-fated @beartype 0.18.0 release. The heavens themselves unleashed Hellish Displeasure. Now, I choose wisely.
The new motto is:
Release late. Release infrequently. Release safely.
On the bright side, "Release safely." is good! We can all agree. On the dark side, "Release late." and "Release infrequently." are both bad. We still agree. But one out of two ain't bad. Right?
<sup>that feeling when you realize it isn't even two out of three</sup>
Finally. The Big Bear has landed.
Finally. The Big Bear has landed.
@beartype 0.19.0 release candidate 1 – the second (and better-be final) beta pre-prelease of the zombified @beartype 0.19.0 release cycle that I should have released three months ago – lands in your lap with a suspicious quacking noise. You're startled. You shriek in dismay! And that's when you hear it. A knock on the door. Muffled voices from the hallway. Disconcertingly familiar, you feel like you almost understand what's going on:
Code Lieutenant: I think we can handle one little beta release. I sent two unit tests. They're bringing it down now. Agent Leycec: No, Code Lieutenant. Your bugs are already dead.
@beartype 0.19.0rc1 politely hiccups. Yet the struggle for your codebase has only just begun:
pip install --upgrade --pre beartype # <-- sound of bugs panicking distantly heard
@beartype 0.19.0rc1 is brought to you by Ultros, a purple octopus in dire need of dental work.
<sup>your bugs are up the creek without a paddle! and @beartype isn't going to let them through! does that make @beartype a good Bear?</sup>
Okay. Okay. Ultros didn't do nuffin' except lie about on a raft all day and try to eat heroes. Let's try again.
@beartype 0.19.0rc1 is actually brought to you by...
This release comes courtesy these proud GitHub Sponsors, without whom @leycec's cats would currently be eating grasshoppers:
Thanks so much, masters of fintech and metrology.
<sup>The Masters of Fintech and Metrology. That's who.</sup>
infer_hint(): Because you hate type hints, make @beartype write them all for youType hints are the most compact description of the internal structure of your objects. If you know the type hint for an object, you know the object better than the object knows itself. Type hints are thus the optimal documentation. Unlike docstrings, type hints never lie or @beartype breaks your app. Type hints are both human-readable and machine-readable. They're literally the only thing that is.
Many type hints are trivial to write. All of us can sling around breazy list[int] | None type hints while yawning. It's not impressive. My cats can write that type hint with one sleepless eye open. Seriously. Why do cats sleep with one eye open, anyway? Doesn't that kinda defeat the purpose of... I dunno, sleeping? Must suck to be a paranoid cat. Uhhh. Back to the discussion.
Some type hints, however, are non-trivial. You can't write them. Nobody can. They contain more square brackets than the final dungeon of 80's ASCII BOFH terminal darling Rogue. When your type hint looks like this, the end of code maintainability cannot be far:
<sup>that smiling face is you hammering the commit button despite CI failures from @beartype.</sup>
Moreover, you don't even know the internal structure of most objects. Somebody else wrote those objects. They forgot how those objects worked a hot minute after clocking out at 4:12AM seven days deep into a crunch-time death march last January. They documented how those objects worked, but their documentation doesn't make sense and lies about everything. Now, nobody knows how those objects work.
But what if somebody did know how those objects work? What if somebody knew Python better than Python knew itself? Introducing... that somebody.
infer_hint(): Deep Introspection for the Deep Code DiverLet @beartype ease your weary burden, traveller. It is dangerous to go alone:
# Crazy object you could understand. But... ain't nobody got that kinda time.
>>> from pygments.lexers import PythonLexer
>>> root_tokens = PythonLexer().tokens["root"]
# I've got a crazy object here, @beartype. What's the crazy type hint that
# matches my crazy object? This is gonna really suck. I can *FEEL* it coming
# through my monitor tonight.
>>> from beartype.door import infer_hint
>>> infer_hint(root_tokens)
list[ # <-- what could possibly go wrong?
typing.Union[ # <-- sucky stuff starts
tuple[str | collections.abc.Callable[typing.Concatenate[object, object, ...], object], ...], # <-- sucky stuff intensifies
tuple[str | pygments.token._TokenType[str], ...], # <-- so much sucky stuff
typing.Annotated[collections.abc.Collection[str], beartype.vale.IsInstance[pygments.lexer.include]] # <-- go to heck, typing!
]
] # <-- i have no idea and neither do you
...uhh. If you say so, @beartype. I guess? </weeps_in_square_bracket_hell>
<sup>what it feels like to live in Canada, friends.</sup>
beartype.door.infer_hint() (i.e., the algorithm hereafter known simply as BeartypeAI™) knows all about deep introspection of arbitrarily complex objects. Here's what BeartypeAI™ knows:
BeartypeAI™: "I know that your type hints kinda suck. Wait... where are your type hints? I'm panicking. I'm panicking." you: "Tell my team something my team don't know, BeartypeAI™. We hate type hints. So we don't do type hints. We code instead. You should try it sometime. But... aren't you a type-checking bear? Can you even code with paws?" BeartypeAI™: "Hold my QA beer."
BeartypeAI™ is here to tell you something you don't know and wouldn't care about even if you did.
BeartypeAI™ is here to write your type hints for you. Why? Because you hate type hints. Just:
beartype.door.infer_hint() arbitrarily complex objects.It's impossible to unpack how much madness is happening inside BeartypeAI™. Let's try anyway.
<sup>son of a submariner bounces on the hot sand like bugs across your git log.</sup>
We've all been there. Some "genius"-tier wise guy devbro invented his own homebrew pure-Python collection called WeirdoCustomList without subclassing a standard collections.abc abstract base class. Sure, they could have just subclassed collections.abc.MutableSequence to write their special-needs alternative to the builtin list type. That would have been too easy. They're a masochist, so they wrote everything from scratch.
Homebrew collections are more common than you think. They're friggin' everywhere! They're multiplying like meat flies! The cat's choking on bloody homebrow collections! Look above, for example. See that nasty typing.Annotated[collections.abc.Collection[str], IsInstance[pygments.lexer.include]] type hint that BeartypeAI™ wrote for you? Yeah.
That's right. The public pygments.lexer.include type is actually a homebrew collection. They thought they were being smart. Sadly, they were being dumb. Because they wrote a homebrew collection from scratch, their collection type is unsubscriptable. You can't subscript it with child type hints like with list[str], so you can't use their collection type as a type hint factory to write type hints, so you can't actually validate their homebrew collection. In fact, you can't validate any homebrew collections.
...until now. BeartypeAI™ knows all about homebrew collections. BeartypeAI™ knows that you can actually validate homebrew collections – but only if you write a custom beartype validator leveraging the PEP 593-compliant typing.Annotated[...] type hint factory in concert with the @beartype-specific beartype.vale.IsInstance[...] validator. Please don't do this manually. You value your precious life force that is leaking all over your keyboard as we speak.
That's what the typing.Annotated[collections.abc.Collection[str], IsInstance[pygments.lexer.include]] type hint is all about. BeartypeAI™ correctly detected that this homebrew collection is actually just an instance of the pygments.lexer.include class that is externally usable as a collection of strings.
Let's get more explicit. Nobody understands pygments – not even pygments. Instead, consider...
<sup>this is for @Moosems!</sup>
It's... it's hideous!
from beartype.door import infer_hint
from collections.abc import Iterable, Iterator
# Define a weirdo custom list.
class WeirdoCustomList(object):
'''
Weirdo custom list. The one. The only.
Weirdo custom list pretends to mean no harm. Weirdo custom list is
lonely at night and only wants to be snuggle-friends. *How could you
refuse weirdo custom list in its example of need?*
'''
def __init__(self, items: list) -> None: self._items = items
def __contains__(self, item: object) -> bool: return item in self._items
def __iter__(self) -> Iterator: return iter(self._items)
def __len__(self) -> int: return len(self._items)
def __getitem__(self, index: int) -> object: return self._items[index]
def __reversed__(self) -> Iterator: return reversed(self._items)
def count(self, item: object) -> int: return self._items.count(item)
def index(self, *args, **kwargs) -> int:
return self._items.index(*args, **kwargs)
def __delitem__(self, index: int) -> None: del self._items[index]
def __setitem__(self, index: int, item: object) -> None:
self._items[index] = item
def __iadd__(self, item: object) -> object: self._items += item
def append(self, item: object) -> None: self._items.append(item)
def clear(self) -> None: self._items.clear()
def extend(self, items: Iterable) -> None: self._items.extend(items)
def insert(self, index: int, item: object) -> None:
self._items.insert(index, item)
def pop(self, *args, **kwargs) -> object:
return self._items.pop(*args, **kwargs)
def remove(self, item: object) -> None: self._items.remove(item)
def reverse(self) -> None: self._items.reverse()
# Infer the type hint for a weirdo custom list of strings.
print(infer_hint(WeirdoCustomList([
'No way,', '@beartype.', 'No.', "Friggin'.", 'Way.'])))
...which prints:
typing.Annotated[collections.abc.MutableSequence[str], IsInstance[WeirdoCustomList]]
"What's so hot about that?", you may now be thinking. Allow me to now pontificate boringly.
WeirdoCustomList isn't subscriptable. It's not a type hint factory. Moreover, despite being a mutable sequence, WeirdoCustomList doesn't actually subclass the standard collections.abc.MutableSequence protocol. Yet, @beartype correctly detected that this particular weirdo custom list is a mutable sequence of strings. How? It's best not to ask weirdo custom list these questions. :rofl:
<sup>a lone dev seeks the calm in the midst of the bug storm, yet finds only a rainbow</sup>
Callable[...] Type Hints: Gods, They Suck.Annotating callables (especially callbacks) with PEP-compliant Callable[...] type hints is basically impossible. Personally, I've never gotten a single Callable[...] type hint to work right. They never match the callables they're supposed to when I write them myself. mypy and pyright always vomit all over themselves and then me. I mostly just give up now and use the unsubscripted collections.abc.Callable abstract base class instead of full-blown Callable[...] type hints...
...until now. BeartypeAI™ knows literally everything there is to know about annotating callables. What doesn't BeartypeAI™ know? Well, friends:
BeartypeAI™ knows that a lambda function accepting no parameters is annotated as...
>>> infer_hint(lambda: "No. Friggin'. Way.")
collections.abc.Callable[[], object] # <-- woah
BeartypeAI™ knows that a lambda function accepting multiple parameters is annotated as...
>>> infer_hint(lambda you, will, believe: "@beartype, I am your code father.")
collections.abc.Callable[[object, object, object], object] # <-- i don't know what's happening here, but i like it
BeartypeAI™ knows that a normal function accepting two mandatory annotated parameters and one optional annotated parameter is "best" annotated with a PEP 612-compliant typing.Concatenate[...] subscription as...
>>> def i_am_tired(this: float, so: int, boring: str = "y u so boring, @beartype!?"): ...
>>> infer_hint(i_am_tired)
collections.abc.Callable[typing.Concatenate[float, int, ...], object] # <-- don't ask, just accept.
BeartypeAI™ knows that a decorator wrapper function accepting a PEP 612-compliant parameter specification is annotated as...
>>> from typing import ParamSpec
>>> P = ParamSpec('P')
>>> def so_param_so_spec(*args: P.args, **kwargs: P.kwargs): ...
>>> infer_hint(so_param_so_spec)
collections.abc.Callable[~P, object] # <-- yer frickin' blowin' mah mind here, yo
BeartypeAI™ knows that a decorator wrapper function accepting two mandatory annotated parameters followed by a PEP 612-compliant parameter specification is annotated with a PEP 612-compliant typing.Concatenate[...] subscription as...
>>> from typing import ParamSpec
>>> P = ParamSpec('P')
>>> def more_param_more_spec(
... go_crazy: int,
... dont_mind_if_i_do: str,
... *args: P.args,
... **kwargs: P.kwargs
... ): ...
>>> infer_hint(more_param_more_spec)
collections.abc.Callable[typing.Concatenate[int, str, ~P], object] # <-- pretty sure the universe just exploded
What I'm trying to say here is that BeartypeAI™ knows all and sees all and doesn't like it what it sees, but is still doing it's best for everybody. It knows more than me. It probably knows more than even you, even though you know everything. That's how much BeartypeAI™ knows.
<sup>@beartype casts Meteor Suplex on the runaway train that is your codebase</sup>
Tensor type hints really suck. So your team wants to annotate NumPy, JAX, PyTorch, or TensorFlow arrays, huh? That's a perfectly reasonable request. Too bad, though. Because tensor type hints suck.
Tensor type hints suck so bad you have to use third-party packages like jaxtyping just to make them work, despite the fact that both NumPy and JAX ship type hint-centric subpackages like numpy.typing and jax.typing that are supposed to make tensor type hints "just work." Of course, tensor type hints don't "just work." They don't even work...
...until now. BeartypeAI™ knows literally everything there is to know about annotating tensor type hints. Actually, that's a lie. I really wanted BeartypeAI™ to know literally everything there is to know about annotating tensor type hints in time for @beartype 0.19.0rc1. Sadly, I played video games instead. I only got around to implementing BeartypeAI™ support for inferring NumPy tensor type hints.
Still, NumPy is better than nothing. One out of four ain't bad. Right? ...anybody? :face_exhaling:
# Define the greatest NumPy array that has ever existed.
>>> from numpy import asarray
>>> best_array_is_best = asarray((1, 0, 3, 5, 2, 6, 4, 9, 2, 3, 8, 4, 1, 3, 7, 7, 5, 0,))
# Create a type hint validating that array, @beartype! Look. Just do it.
>>> from beartype.door import infer_hint
>>> infer_hint(best_array_is_best)
typing.Annotated[numpy.NDArray[int], beartype.vale.IsAttr['ndim', beartype.vale.IsEqual[1]]] # <-- wtf, @beartype
And... that's the type hint. That type hint requires no third-party dependencies. It's all @beartype, all one-liner. Nobody's writing that sort of gruelling bracket hell on their own. Not even @leycec. Now, just let somebody else do all the suffering for you. That somebody is @beartype. Who knew?
<sup>don't be that one guy who falls off the floating island. just... don't</sup> <sup></sup>
The new beartype.door.infer_hint() function tidily combines with the existing beartype.door.is_bearable() tester to create a new monstrous form of Python object test: structural similarity. But let's back up. In the beginning, there was:
# The "is" operator. Test whether two objects are literally identical.
>>> "I like big bugs and I cannot lie." is "I like big bugs and I cannot lie."
True
# The "==" operator. Test whether two objects are semantically identical.
>>> ['Other', 'devbros', 'may', 'deny',] == ['Other', 'devbros', 'may', 'deny',]
True
But what if you want to test whether two objects are structurally similar (i.e., have a similar internal structure but are neither literally nor semantically identical)? Without BeartypeAI™, you can't do that. But you have BeartypeAI™. You no longer have to accept the mouldy table scraps that the standard Python library has left you. Why? Because you have harnessed the perfidious power of beartype.door.infer_hint() + beartype.door.is_bearable(). Arise, a new darkness!
>>> from beartype.door import infer_hint, is_bearable # <-- boring stuff
# Excitement builds. Declare data structures for great glory of your code.
>>> awesome_data_structure = [{"uhh...": int, "wat!?!": [lambda: None]}, 0xFEEEEEEED]
>>> baleful_data_structure = [0xBABEEEE, {"ohgod": [lambda: True], "NOOOO!": object}]
# Describe the internal structure of your great glory.
>>> infer_hint(awesome_data_structure)
list[dict[str, type[int] | list[collections.abc.Callable[[], object]]] | int] # <-- ok
>>> infer_hint(baleful_data_structure)
list[dict[str, type[int] | list[collections.abc.Callable[[], object]]] | int] # <-- i don't know. sure, i guess?
# Do these two objects have a similar internal structure?
>>> is_bearable(baleful_data_structure, infer_hint(awesome_data_structure))
True # <----- WTF-F-F-F-F-
Structural similarity: when you care about what your objects care about.
<sup>so tired. so very, very tired.</sup>
@pablovela5620, @thiswillbeyourgithub, @WeepingClown13, @JWCS, @Logan-Pageler, @knyazer, @Moosems, @frrad, @minmax, @jaanli, @jonnyhyman, @f-fuchs, @jennydaman, @denballakh, @bionicles
Welcome. Welcome, one and all bearthonistas, to the Bear Beta Fan Club. Congrats. You're reading this, so you're automatically in the club. Everyone w
Welcome. Welcome, one and all bearthonistas, to the Bear Beta Fan Club. Congrats. You're reading this, so you're automatically in the club. Everyone who has submitted an issue in the last year has been pinged onto this announcement. If you hate @beartype or love @beartype but hate your codebase, simply unsubscribe from this announcement and watch as your codebase burns against the night sky. It's fine. "The burning means it works!", you tell your coworkers.
Beartype 0.19.0 Release Candidate 0 is the inaugural publication of @beartype's first of many painfully broken well-tested pre-releases. If you or someone you love uses @beartype, consider manually upgrading to this pre-release and reporting all painful breakage to your nearest @beartype issue tracker. Note that installing pre-release versions with pip requires manually passing the --pre option on the command-line:
pip install --upgrade --pre beartype # <-- LET THE THUNDER AND THE HEADS ROLL
You may now be thinking:
"What is this eldritch darkness in my GitHub feed?"
Allow QA-Daddy @leycec to now gently exhaust you on a Friday evening.
<sup>Bear Beta Fan Club members pass out from general excitement</sup>
@beartype 0.18.0 broke the entire world. @leycec can now admit that to himself while clutching his Maine Coon teddy cat. If your codebase survived @beartype 0.18.0, you deserve an "I Survived @beartype 0.18.0 and All I Got Was This Lousy Badge" badge. The ill-fated @beartype 0.18.0 release cycle that nearly broke my fingers taught me many things: suffering, pain, agony, blah, blah... You know. Just the standard stuff, really.
@beartype 0.18.0 taught me that @beartype has become a lot bigger than me. Other people and people-like AI that are doing meaningful things with their lives and synthetic lives (respectively) now depend on new @beartype releases not throwing up all over everybody.
@beartype ≥ 0.19.0 intends to avoid that throw-up. Several days before releasing any new major version like 0.19.0, 0.20.0, or 0.21.0: <sup>...we see the number sequence I trust</sup>
Basically, I'm just doing standard beta releases now. That's all I had to say. Instead, I laboriously enumerated a workflow that doesn't really make sense when you squint at it. Oh, well. This too was wasted time.
The sins of the fathers must never be repeated. Never forget @beartype 0.18.0! Never forgive @leycec! Wait. Shouldn't @leycec be forgiven already at some point!? <sup><-- dat poor guy</sup>
<sup>Bear Beta Fan Club members have no one to blame but @leycec</sup>
A whole lot, probably. @beartype 0.19.0:
--disable-gil compile-time option. Yes! YES! YEEEEEEESSSSS!!!! Wait. Where am I? What are these fingers on this keyboard? This must be what good dreams are typed of.--enable-experimental-jit compile-time option. OMMMMMMMMMMMMMMMMG..... It's happening. It's really happening. My breathing is now laboured and making awkwardly squishy noises that upset the cat.setuptools + setup.py <sup> :vomiting_face: </sup> to Hatch + pyproject.toml <sup> :clinking_glasses: </sup>. It went great, actually. Thanks for asking. I highly recommend Hatch for all projects – new and old. It's like Rust's Cargo, only Python. It actually works, unlike everything else. Hatch: because you're too bald to fight with Python anymore. Caveat emptor:
setuptools) at build time. If your packaging ecosystem also packages Hatch, this is trivial. Else, I sympathize with your growing toothache but can do nothing for you. Emoji man sighs. :face_exhaling:O(1) type-checks a ton of fun containers I've loosely categorized as reiterables (i.e., collections satisfying the collections.abc.Collection protocol with guaranteed O(1) read-only access to only the first collection item). Reiterables include sets, frozen sets, dictionary views, deques (i.e., double-ended queues), and all other containers matched by one or more of the following PEP 484- or 585-compliant type hints:
frozenset[...].set[...].collections.deque[...].collections.abc.Collection[...].collections.abc.KeysView[...].collections.abc.MutableSet[...].collections.abc.Set[...].collections.abc.ValuesView[...].typing.AbstractSet[...].typing.Collection[...].typing.Deque[...].typing.FrozenSet[...].typing.KeysView[...].typing.MutableSet[...].typing.Set[...].typing.ValuesView[...].@equinox.filter_jit and @jax.jit decorators. In fact, @beartype now generically supports all pseudo-callable wrapper objects (i.e., objects defining both the __call__() and __wrapped__ dunder attributes). The @beartype decorator may now be chained (i.e., listed) either below or above the third-party @equinox.filter_jit and @jax.jit decorators. Since all beartype.claw import hooks (e.g., beartype.claw.beartype_this_package()) forcefully chain @beartype above all other decorators, all @beartype import hooks now transparently support:
@equinox.filter_jit decorator.@jax.jit decorator.
<sup>Bear Beta Fan Club member after going --disable-gil + --enable-experimental-jit</sup>
Last but never least, the most important part...
This release comes courtesy these proud GitHub Sponsors, without whom @leycec's cats would currently be eating grasshoppers:
Thanks so much, masters of fintech and metrology.
<sup>The Masters of Fintech and Metrology. That's who.</sup>
Announcing the Bear Beta Fan Club from the ashes of our issue tracker:
@posita, @wesselb, @iamrecursion, @patrick-kidger, @langfield, @JelleZijlstra, @RobPasMue, @GithubCamouflaged, @kloczek, @uriyasama, @danielgafni, @JWCS, @rbroderi, @AlanCoding, @tvdboom, @crypdick, @jvesely, @komodovaran, @kaparoo, @MaximilienLC, @fleimgruber, @EtaoinWu, @alexoshin, @gabrieldemarmiesse, @James4Ever0, @NLPShenanigans, @rtbs-dev, @yurivict, @st--, @murphyk, @dosisod, @Rogdham, @alisaifee, @denisrosset, @damarro3, @ruancomelli, @jondequinor, @harshita-gupta, @jakebailey, @denballakh, @jaanli, @creatorrr, @msvensson222, @avolchek, @femtomc, @AdrienPensart, @jakelongo, @Artur-Galstyan, @ArneBachmann, @danielward27, @WeepingClown13, @rbnhd, @radomirgr, @rwiegan, @brettc, @spagdoon0411, @helderco, @paulwouters, @jamesbraza, @dcharatan, @kasium, @AdrienPensart, @sunildkumar, @peske, @mentalisttraceur, @awf, @PhilipVinc, @dcharatan, @empyrealapp, @rlkelly, @KyleKing, @skeggse, @RomainBrault
<sup>unsure what's happening here but it kinda don't seem right</sup>
The @beartype 0.18.X release cycle continues to *bear* lukewarm fruit that tastes vaguely starchy. It's cheap and smells faintly of kerosene. It keeps
The @beartype 0.18.X release cycle continues to bear lukewarm fruit that tastes vaguely starchy. It's cheap and smells faintly of kerosene. It keeps the hunger at bay even as it fails to fully satiate.
Beartype 0.18.5 preserves this trend by resolving... just a single issue! Beartype 0.18.5 resolves a critical low-level issue in @beartype's dynamic type-checking code generator for nested beartype validator-in-container type hints (e.g., type hints of the form list[typing.Annotated[{type}, Is[{validator}]]]). Someone, somewhere cares deeply about this. You might even be that someone.
Hype is completely out the window at this point, everybody. We're just hardening the fat-packed abs of the bear against critical breakage, because your codebase matters more to us than our sleep. And now...
This release comes courtesy these proud GitHub Sponsors, without whom @leycec's cats would currently be eating grasshoppers:
Thanks so much, masters of fintech and metrology.
<sup>The Masters of Fintech and Metrology. That's who.</sup>
The @beartype 0.18.X release cycle continues to *bear* lukewarm fruit that tastes vaguely starchy. It's cheap and smells faintly of kerosene. It keeps
The @beartype 0.18.X release cycle continues to bear lukewarm fruit that tastes vaguely starchy. It's cheap and smells faintly of kerosene. It keeps the hunger at bay even as it fails to fully satiate.
Beartype 0.18.4 preserves this trend by resolving... just a single issue! Beartype 0.18.4 resolves a critical low-level issue in @beartype's dynamic type-checking code generator for nested tuple-in-dictionary type hints (i.e., type hints of the form dict[tuple[...], ...]). Someone, somewhere cares deeply about this. You might even be that someone.
Hype is completely out the window at this point, everybody. We're just hardening the fat-packed abs of the bear against critical breakage, because your codebase matters more to us than our sleep. And now...
This release comes courtesy these proud GitHub Sponsors, without whom @leycec's cats would currently be eating grasshoppers:
Thanks so much, masters of fintech and metrology.
<sup>The Masters of Fintech and Metrology. That's who.</sup>
Beartype 0.18.3 is the minor patch release that your careening codebase can no longer live without:
Beartype 0.18.3 is the minor patch release that your careening codebase can no longer live without:
pip install --upgrade beartype
Actually... I lied. I know! I gotta stop doing that. But the sordid truth is that beartype 0.18.3 is mostly just for @iamrecursion and @sylvorg, who single-handedly reported more issues in a single week than the exploding size of @leycec's JRPG backlog. And we know how big that is, don't we? It's big. It's so big it wraps around like a self-sustaining Niven ringworld habitat at Lagrange point L1. Big-big.
Beartype 0.18.3 is for @iamrecursion and @sylvorg. May their usernames live forever in git log infamy. In this release, a few more bugs die.
But first...
This release comes courtesy these proud GitHub Sponsors, without whom @leycec's cats would currently be eating grasshoppers:
Thanks so much, masters of fintech and metrology.
<sup>The Masters of Fintech and Metrology. That's who.</sup>
So. Funny story. Turns out you can bound PEP 484-compliant type variables (i.e., typing.TypeVar(...) objects) with forward references specified as strings. Who knew? Everybody except @leycec. Nobody tells that guy nuthin'.
Beartype 0.18.3 now explicitly supports type variables bound by forward references. These are type hints of the form:
TypeVar('{TypeVarName}', bounds='{UndefinedType}')
Previously, @beartype only partially supported such variables due to @leycec failing to realize that such variables even existed and constituted a valid use case. This is why your codebase can't have good things. Now, @beartype fully supports heinous abominations valid use cases like:
from beartype import beartype
from typing import TypeVar
# Type variable bound by a forward reference. @beartype supports your
# weird stuff, because normalcy is just a null pointer to garbage.
Fuggit = TypeVar('Fuggit', bound='EnduringMisery')
@beartype
class EnduringMisery(object):
def searing_pain(self) -> tuple[Fuggit, Fuggit]:
return ('Fuggit...', '...up!')
# Can anyone guess what this does? That's right. It blows up. Fuggit!
blinding_agony = EnduringMisery()
blinding_agony.searing_pain()
<sup>hangin' with the bear homies in apocalyptic wasteland ain't no thang</sup>
beartype.vale.Is[...]: Now It Supports Crazy StuffThe functional beartype validator factory beartype.vale.Is[...] is now subscriptable (indexable) by all manner of shambolic nightmares. Previously, you had to subscript Is[...] with low-level functions and methods. Now, you can subscript Is[...] with high-level callable objects like:
Class-based callables (i.e., objects whose classes define the __call__() dunder method, rendering otherwise uncallable objects callable): e.g.,
from beartype.door import is_bearable
from beartype.typing import Annotated
from beartype.vale import Is
from functools import partial
class TruthSeeker(object):
def __call__(self, obj: object) -> bool:
'''
Tester method returning :data:`True` only if the passed object
evaluates to :data:`True` when coerced into a boolean and whose
first parameter is ignorable.
'''
return bool(obj)
# Beartype validator matching only objects that evaluate to "True".
Truthy = Annotated[object, Is[TruthSeeker()]]
assert is_bearable('', Truthy) is False
assert is_bearable('Even lies are true now, huh?', Truthy) is True
Partials (i.e., high-level functools.partial(...) callable objects wrapping low-level functions and methods): e.g.,
from beartype.door import is_bearable
from beartype.typing import Annotated
from beartype.vale import Is
from functools import partial
def is_true(ignorable_arg, obj):
'''
Tester function returning :data:`True` only if the passed object
evaluates to :data:`True` when coerced into a boolean and whose first
parameter is ignorable.
'''
return bool(obj)
# Partial of the is_true() tester defined above, effectively ignoring the
# "ignorable_arg" parameter accepted by that tester.
is_true_partial = partial(is_true, 'Gods. This code is literally unreadable.')
# Beartype validator matching only objects that evaluate to "True".
Truthy = Annotated[object, Is[is_true_partial]]
assert is_bearable('', Truthy) is False
assert is_bearable('Even lies are true now, huh?', Truthy) is True
Is this valuable? No idea. Let's pretend I did something useful tonight so I can sleep without self-recrimination.
<sup>...heh. your eyes are now bleeding</sup>
Beartype 0.18.3 now sports improved support <sup>we rhymin' like it's 2099 ova here</sup> for Jupyter Notebook cells. Do you like Jupyter? Do you like @beartype? Then you need beartype 0.18.3 now, because beartype 0.18.2 probably already broke everything without your informed consent. Woops.
Beartype 0.18.3 resolves inscrutable non-determinism (which is technically deterministic if you squint at it, but we don't talk about that) with respect to repeatedly redefined classes defining one or more methods annotated by one or more self-referential relative forward reference (i.e., referring to the class currently being defined). @beartype is now considerably more robust against non-determinism in Jupyter cells containing @beartype-decorated self-referential classes like:
from beartype import beartype
@beartype
class MuhSelfReferentialClass(object):
def __init__(self, muh_var: int) -> None:
self.muh_var = muh_var
@classmethod
def muh_factory(cls, muh_var: int) -> "MuhSelfReferentialClass":
'''
This is fine now. No matter how much you reload the cell
defining this class, @beartype will still stan for you.
I have no idea what "stan" even means. I think it's good.
'''
return MuhSelfReferentialClass(muh_var + 42)
muh_object = MuhSelfReferentialClass.muh_factory(42)
Flex those burly QA biceps, @beartype. Flex 'em.
<sup>things explode when you put @beartype back in the sheath</sup>
__class_getitem__ = classmethod(GenericAlias): We Do That Too, Whatever That IsSo. You want to refactor your heroic class that will truly shape the course of human history into a subscriptable type hint factory. You even know about the convenient but unreadable one-line idiom for casting this dark magic. Previously, @beartype refused to support your bad habits arcane knowledge. Now, @beartype understands and appreciates everything you're trying to do for humanity.
Beartype 0.18.3 generalizes the @beartype decorator to support decoration of user-defined types that declare class methods by directly calling the builtin @classmethod decorator as a function passed a C-based callable type (e.g., classmethod(types.GenericAlias)). Doing so enables @beartype to support the standard idiom for user-defined subscriptable type hint factories under Python >= 3.9:
from abc import ABCMeta
from beartype import beartype
from types import GenericAlias
@beartype
class MuhTypeHintFactory(metaclass=ABCMeta):
'''
Congrats. Subscripting this class now trivially makes new type hints
that @beartype fails to understand or appreciate.
'''
# This exact one liner appears verbatim throughout the standard
# library as well as popular third-party packages like NumPy.
__class_getitem__ = classmethod(GenericAlias)
# Not sure what this means, but you insist you know what you're doing.
# *Do* you, though? *Do* you? @beartype is out to lunch on this one.
MuhTypeHint = MuhTypeHintFactory[str]
<sup>the pancakes get me every time. srsly. what is with those pancakes?</sup>
Beartype 0.18.3 deprioritizes @beartype-specific forward reference proxies (i.e., internal objects proxying external user-defined types that have yet to be defined) in type tuples passed as the second arguments to the isinstance() builtin, reducing the likelihood that type-checks involving forward references will raise unexpected exceptions. For example, consider this simple example:
from beartype import beartype
from beartype.typing import Union
@beartype
def explosive_funk(muh_arg: Union['UndefinedType', None] = None):
print("You thought this was gonna blow up, huh? You're not alone.")
print("Unless you're in space. In which case you're really alone.")
explosive_funk()
class UndefinedType(object): ...
...which unexpectedly prints without blowing up:
You thought this was gonna blow up, huh? You're not alone.
Unless you're in space. In which case you're really alone.
@beartype type-checks that the default value of the optional muh_arg parameter of the muh_func() function satisfies the type hint 'UndefinedType' | None – despite the fact that the UndefinedType class is undefined! To do so, @beartype now internally reorders the types comprising this union:
# ...from this default type-check, which would raise a decoration-time
# exception due to "UndefinedType" being undefined...
isinstance(muh_arg, (UndefinedTypeProxy, NoneType))
# ...to this default type-check, which should raise *NO* decoration-time
# exception. Why? Because the default value "None" for the "muh_arg"
# parameter satisfies the first "NoneType" type, which then
# short-circuits the isinstance() call and thus ignores the problematic
# "UndefinedTypeProxy" type altogether.
isinstance(muh_arg, (NoneType, UndefinedTypeProxy))
Nobody should ever depend upon this. Therefore, this is a delicious nothingburger – but a delicious nothingburger that could yield future delights in the event that we actually elect to try type-checking defaults at decoration time again. We're not, of course. That would be foolish and dangerous. <sup>We're absolutely going to do that again.</sup>
<sup>rub those cat cheeks! rub 'em!</sup>
Beartype 0.18.3 resolves a subtle interaction between PEP 563 (i.e., from __future__ import annotations), PEP 673 (i.e., typing{_extension}.Self), and common dunder methods like... uh, __add__(), I guess. Let's pretend that's common.
Beartype 0.18.3 ensures that the type stack encapsulating the current @beartype-decorated class is now preserved throughout the type-checking process for standard dunder methods annotated by one or more PEP 673-compliant typing{_extension}.Self type hints that are stringified under PEP 563. For example, @beartype now transparently supports pernicious edge cases resembling:
from beartype import beartype
from typing_extensions import Self
@beartype
class MyClass:
attribute: int
def __init__(self, attr: int) -> None:
self.attribute = attr
def __add__(self, other: int) -> Self:
self.__class__(self.attribute + other)
If you wanted this, you are literally @iamrecursion. Congrats.
<sup>you too will believe that @beartype 0.18.3 actually works</sup>
Pinging @posita, @iamrecursion, @sylvorg, @tactile-metrology, @kalaspuff, @danielward27, @kloczek, @uriyasama, @danielgafni, @JWCS, @rbroderi, @AlanCoding, @tvdboom, @crypdick, @WeepingClown13, @RobPasMue, @rbnhd, @radomirgr, @rbroderi.
You are wanted on floor 13. Japanese buildings don't even have a floor 13. Surely nothing could go wrong by violating that fundamental.
<sup>those dance moves can mean only one thing... This was @beartype 0.18.3.</sup>
Much like your neighbour's obese cat, even @beartype 0.18.1 didn't quite work out as expected. This patch release temporarily squelches (i.e., silence
Much like your neighbour's obese cat, even @beartype 0.18.1 didn't quite work out as expected. This patch release temporarily squelches (i.e., silences) a low-level assert statement erroneously performed during @beartype's dynamic code generation loop. Is this the end to the horror show that keeps on giving? Will the ill-fated @beartype 0.18.x release cycle finally pass muster and stop violating the world? Tune in next time as @leycec clutches his chest in agony live on GitHub.
Obligatory awesome peeps!
This release comes courtesy these proud GitHub Sponsors, without whom @leycec's cats would currently be eating grasshoppers:
Thanks so much, masters of fintech.
<sup>The Masters of Fintech. That's who.</sup>
Much like your neighbour's obese cat, @beartype 0.18.0 didn't quite work out as expected. This patch release temporarily reverts default value type-ch
Much like your neighbour's obese cat, @beartype 0.18.0 didn't quite work out as expected. This patch release temporarily reverts default value type-checking (i.e., type-checking of default values of optional parameters annotated by type hints accepted by @beartype-decorated callables), restoring sanity to the downstream community of @beartype consumers.
Although desirable, this functionality is also a lot more nuanced than @leycec previously assumed -- resulting in @leycec clutching his bald head as if he still had something to clutch there. Since improving this functionality to be robust against breakage is non-trivial, the proper solution is to temporarily disable that functionality. Thus, we cry.
Obligatory awesome peeps!
This release comes courtesy these proud GitHub Sponsors, without whom @leycec's cats would currently be eating grasshoppers:
Thanks so much, masters of fintech.
<sup>The Masters of Fintech. That's who.</sup>
Does anyone even care about deprecations anymore? *Everything* in the standard typing package has now been deprecated. When everything is deprecated,…
Beartype 0.18.0 whimsically gyrates around in balloon pants while chanting: "Can't touch this."
<sup>...even the token bald man in a smoking post-apocalyptic wasteland doesn't know</sup>
It's kinda creepy, honestly – and it's really getting on your nerves. Yes, we get it. You think you're hot junk, @beartype 0.18.0! Yet you can't help but admire the sweat that coats its body. Beartype 0.18.0 worked out for this release. It's buff now. It's tough now. It does things now. It does things you thought it did five years ago now. Beartype 0.18.0 finally caught up to your expectations. It even tried to exceed them. It didn't, of course. It couldn't. It's only a bear. It rarely bathes. And, anyway, your expectations were unreasonable.
But... it almost did. Prepare to have your expectations almost exceeded:
pip install --upgrade beartype
But what is @beartype 0.18.0? What does it do? Nuthing, huh? It's all just hollow hype and empty promises again, huh?
To answer that reasonable question, let's unreasonably back up with an extended monologue while the camera man slow pans across @leycec's baldpate. What was @beartype < 0.18.0? Why would anyone actually suffer install older @beartype releases? In the anachronistic words of an inconvenient acronym I just made up: scientific quality assurance (SciQA). So you wanna type-check...
jaxtyping. :kissing_heart:pandera. :hugs:typing oblivion. :smiling_face_with_tear:We're agreed that @beartype < 0.18.0 was limited in scope. If you fit inside that scope, your codebase fits inside a backpack. Congratulations. It pays to be lean. But what if you have a real codebase? What if you wanted to actually type-check general-purpose Python containers outside that scope?
You use @beartype 0.18.0! That's right. We're finally type-checking general-purpose Python containers. But first...
Prepare your battle-hardened body and soul for the epic maelstrom of delivered features that follows by watching this malicious YouTube video! Just kidding. It's wholesome. Really. It's Saitama vs. Genos – surely humanity's crowning achievement. Praise be to Arifumi Imai for he has seen the countenance of many small gods and found them all sadly lacking.
@leycec always queues up Saitama vs. Genos when he needs to get hyped. Gonna groom the hair off a scary cat giving you the ugly fish-eyed thousand-yard death grimace? Saitama vs. Genos. Gonna remount your girlfriend's 64-core ThreadInfernoBurner CPU that's already sintered six motherboards into charred thermal paste in the wood shed out back that the sea walruses are rifling through? Saitama vs. Genos. When things get real, you just get realer. Saitama vs. Genos.
<sup>when your shoulders rip off their hinges, you just hope that t-shirt was disposable</sup>
And now...
This release comes courtesy these proud GitHub Sponsors, without whom @leycec's cats would currently be eating grasshoppers:
Thanks so much, masters of fintech.
<sup>The Masters of Fintech. That's who.</sup>
And now... the moment people I have never met have been waiting for.
Beartype 0.18.0 now deeply type-checks the first key-value pair of each dictionary (mapping) annotated by a dictionary (mapping) type hint in O(1) constant time with negligible constant factors. This means near-real-time with runtime overhead of at most ~1µs (i.e., one microsecond, one millionth of a second) per type-check. This includes all hints of the form:
dict[..., ...].collections.defaultdict[..., ...].collections.abc.Mapping[..., ...].collections.abc.MutableMapping[..., ...].collections.abc.OrderedDict[..., ...].typing.DefaultDict[..., ...].typing.Dict[..., ...].typing.Mapping[..., ...].typing.MutableMapping[..., ...].typing.OrderedDict[..., ...].This (...probably) also includes @wesselb's multiple-dispatch pièce de résistance Plum, which should now automatically multiple-dispatch across different kinds of dictionaries without @wesselb actually having to do anything. Let us choose to believe this optimistic prophecy I have delivered.
Beartype 0.18.0 does so (...effectively) recursively on arbitrarily nested combinations and permutations of those type hints. The proof is in the disgusting British blood pudding possibly named something like "toad-in-the-bear-hole":
from beartype import beartype
from collections.abc import Mapping, MutableMapping
@beartype
def go_bear(bear_bros_for_life: dict[
int, Mapping[str, MutableMapping[bytes, bool]]]) -> None:
print(bear_bros_for_life)
# This passes. A beautiful dictionary brings a tear to the eye.
go_bear({
1: {
'Beautiful bird;': {
b'thou voyagest to thine home,': False,
},
},
})
# This fails! A horrible dictionary brings your app crashing to the ground.
go_bear({
1: {
'With thine,': {
b'and welcome thy return with eyes': 1,
},
},
})
Type-checking violation messages even identify the exact key-value pair of arbitrarily complex pure-Python data structures responsible for those violations. The above example now helps you ruin your coworker's all-too-brief web app career by raising:
beartype.roar.BeartypeCallHintParamViolation: Function __main__.go_bear()
parameter bear_bros_for_life={1: {'With thine,': {b'and welcome thy return with eyes': 1}}}
violates type hint dict[int, collections.abc.Mapping[str, collections.abc.MutableMapping[bytes, bool]]],
as dict key int 1 value dict key str 'With thine,' value dict key bytes
b'and welcome thy return with eyes' value int 1 not instance of bool.
Beartype 0.18.0: I swear that looks more readable when you see it in person.
<sup>if my leg ever bends like that, please call for help</sup>
...heh. So, funny story. Apparently, @beartype < 0.18.0 didn't bother type-checking the default values of optional parameters at early @beartype decoration time. Why even bother, right? Beartype < 0.18.0 trusted you against its better judgement. Beartype < 0.18.0 only type-checked the default values of unpassed optional parameters at late function call time; if you always passed optional parameters (or never even called functions that accept optional parameters), @beartype < 0.18.0 never type-checked their defaults. This is why your office luncheons always order take-out that tastes like plastic.
Beartype 0.18.0 conveniently overlooks the abject failings of the distant past by embracing a new normal that you always thought was happening. Now, it is. All default values are now type-checked at early @beartype decoration time – with one prominent exception we're about to get to.
Behold! Type-check defaults at decoration time or go home, @beartype 0.18.0:
from beartype import beartype
@beartype
def beartype_i_am_your_code_father(
nooooooooooooo: int = 'Oh, you will be. You will be.') -> None: ...
Despite the offending (and clearly offensive) beartype_i_am_your_code_father() function not being called, the @beartype decorator now raises the expected type-checking violation at decoration time:
beartype.roar.BeartypeDecorHintParamDefaultViolation: Function
__main__.beartype_i_am_your_code_father() parameter "nooooooooooooo"
default value 'Oh, you will be. You will be.' violates type hint
<class 'int'>, as str 'Oh, you will be. You will be.' not instance of int.
Above, we wrote that:
All default values are now type-checked at early
@beartypedecoration time – with one prominent exception we're about to get to.
What "prominent exception," @beartype? What bald-faced lies are you trying to sell us now, @beartype?!
The prominent exception is forward references. When the type hint annotating an optional parameter contains one or more unresolvable forward references (i.e., references to types that have yet to be defined), the @beartype decorator just issues a non-fatal warning rather than raising a fatal exception. After all, there might be a real problem there – but there might also not be a real problem there. @beartype can't tell, because the type is undefined. So, @beartype just notifies you that something is up. The power is in your hands. The power was always in your hands. After all, you use @beartype: the QA Power Glove.™ <sup>← awkwardly dated 80's moments</sup>
Arise! Ignore unresolvable forward references in optional parameters at decoration time, beartype 0.18.0:
from beartype import beartype
@beartype
def ive_seen_bugs(you_people_wouldnt_believe: 'TearsInTheGitter' = (
'Attack one-liners on fire off the shoulder of GitHub.')) -> None: ...
...which merely issues this non-fatal warning:
BeartypeDecorHintParamDefaultForwardRefWarning: Function
__main__.ive_seen_bugs() parameter "you_people_wouldnt_believe"
default value 'Attack one-liners on fire off the shoulder of GitHub.'
uncheckable at @beartype decoration time, as forward reference
"TearsInTheGitter" unimportable from module "__main__".
@beartype
Beartype 0.18.0: because QA in 2024 is so complicated that you're just passively nodding along in the vain hope that one of these nothingburgers will start making sense.
<sup>if you ever see the Japanese character for death suspended in the air outlined in red letters, @beartype probably can't help you anymore. still, it's worth a try</sup>
typing.TypeGuard + beartype.door.is_bearable(): It's BAAAAAAAAAACKBeartype 0.18.0 resuscitates PEP 647-compliant typing.TypeGuard[T]-based type narrowing on the beartype.door.is_bearable() type-checker. This means that mypy now loves beartype.door.is_bearable() as much as you love your rabid scrappy dog that mauls the jaded postal worker every day:
from beartype.door import is_bearable # <-- *NOW WITH THE POWER OF PEP 647*
def narrow_types_like_a_boss_with_beartype(lst: list[int | str]):
if is_bearable(lst, list[int]):
munch_on_list_of_integers(lst) # <-- mypy now loooves this
elif is_bearable(lst, list[str]):
munch_on_list_of_strings(lst) # <-- mypy love intensifies
def munch_on_list_of_strings(lst: list[str]): ...
def munch_on_list_of_integers(lst: list[int]): ...
This is entirely thanks to a mammoth dissertation-length dissection by Python's unassailable typing genius @asford (Alex Ford) on the intersection <sup>oh gods what does any of this mean anymore</sup> of runtime and static type-checking vis-a-vis the procedural statement-level hybrid runtime-static type-checker beartype.door.is_bearable(), the PEP 484-compliant @typing.overload decorator, and the PEP 647-compliant typing.TypeGuard[T] type hint. Please redirect all blame towards @asford. I barely understand anything anymore.
Sadly:
This does not extend to the comparable object-oriented beartype.door.TypeHint.is_bearable() method – which continues to not perform type narrowing. Due to deficiencies in @leycec's wobbly brain, only the procedural beartype.door.is_bearable() function currently performs type narrowing.
This may not extend to pyright. Although mypy appears to fully support this API, pyright appears to raise fatal errors that make no sense and suggest pyright has an equally wobbly brain:
/home/leycec/py/beartype/beartype/door/_doorcheck.py
/home/leycec/py/beartype/beartype/door/_doorcheck.py:209:5 - error: Overloaded implementation is not consistent with s>
Function return type "TypeGuard[T@is_bearable]" is incompatible with type "bool"
"TypeGuard[T@is_bearable]" is incompatible with "bool" (reportInconsistentOverload)
/home/leycec/py/beartype/beartype/door/_doorcheck.py:209:5 - error: Overloaded implementation is not consistent with s>
Function return type "TypeGuard[T@is_bearable]" is incompatible with type "bool"
"TypeGuard[T@is_bearable]" is incompatible with "bool" (reportInconsistentOverload)
2 errors, 0 warnings, 0 informations
What's "funny" about that is that:
All TypeGuard[...] type hints reduce to and are thus compatible with the standard bool type.
PEP 647 claims that the reference implementation of PEP 647 is (...waitforit) pyright:
The Pyright type checker supports the behavior described in this PEP.
Guess it doesn't, huh? We cry wet crocodile tears for OO and pyright.
Beartype 0.18.0: @leycec cannot be held responsible for his own failings.
<sup>@leycec clutches a living-preserving cup of "matcha on the rocks."</sup>
typing.TypeAlias: It's Deprecated, But That's Okay, Because Literally Everything Is DeprecatedDoes anyone even care about deprecations anymore? Everything in the standard typing package has now been deprecated. When everything is deprecated, nothing is deprecated. The desensitization is real and you no longer care.
Beartype 0.18.0 appreciates your growing sense of futility and vaguely uneasy apprehension of impending doom. After all, @beartype is the codebase built by a playlist of twelve continuous days of stoner caveman doom metal from Dorset. If it's got a reputable name like "Dopesmoker", "Dopethrone", "Shroomaroom", or "Satori", we probably resolved your issue to it without your consent. Bonus GitHub karma to the bear bro that names the album that starts with this well-intended life lesson:
Drop out of life with bong in hand! Follow the smoke to the riff-filled land!
That's why @beartype now officially supports PEPs that are dead that nobody cares about anymore like PEP 613: typing.TypeAlias. Although deprecated by PEP 695 type aliases (e.g., type hints of the form type {alias_name} = {alias_value} under Python ≥ 3.12), PEP 613 type aliases are still widely prevalent throughout the open-source community. Specifically, @beartype now:
Emits an absurd deprecating warning for each PEP 613 type alias that spans five volumes of archaic dead-tree print like that long-lost Brandon Sanderson cyberpunk fantasy saga you always knew existed:
BeartypeDecorHintPep613DeprecationWarning: PEP 613 type hint
typing.TypeAlias deprecated by PEP 695. Consider either:
* Requiring Python >= 3.12 and refactoring PEP 613 type aliases into
PEP 695 type aliases. Note that Python < 3.12 will hate you for
this: e.g.,
# Instead of this...
from typing import TypeAlias
alias_name: TypeAlias = alias_value
# ...just do this.
type alias_name = alias_value
* Refactoring PEP 613 type aliases into PEP 484 "typing.NewType"-based
type aliases. Note that static type-checkers (e.g., mypy, pyright,
Pyre) will hate you for this: e.g.,
# Instead of this...
from typing import TypeAlias
alias_name: TypeAlias = alias_value
# ...just do this.
from typing import NewType
alias_name = NewType("alias_name", alias_value)
Combine the above two approaches via The Ultimate Type Alias (TUTA),
a hidden ninja technique that supports all Python versions and static
type-checkers but may cause coworker heads to pop off like in that one
jolly Kingsman scene:
# Instead of this...
from typing import TypeAlias
alias_name: TypeAlias = alias_value
# ..."just" do this. If you think this sucks, know that you are not alone.
from typing import TYPE_CHECKING, NewType, TypeAlias # <-- sus af
from sys import version_info # <-- code just got real
if TYPE_CHECKING: # <-- if static type-checking, then PEP 613
alias_name: TypeAlias = alias_value # <-- grimdark coding style
elif version_info >= (3, 12): # <-- if Python >= 3.12, then PEP 695
exec("type alias_name = alias_value") # <-- eldritch abomination
else: # <-- if Python < 3.12, then PEP 484
alias_name = NewType("alias_name", alias_value) # <-- coworker gives up here
Otherwise ignores each PEP 613 type alias, which conveys no meaningful semantics or metadata. Frankly, it's unclear why PEP 613 even exists. The CPython developer community felt similarly, which is why PEP 695 type aliases deprecate PEP 613.
Beartype 0.18.0: it's not our fault.
<sup>gettin' kinda queasy watchin' cyborg man spin around like an unsafe carousel on fire</sup>
They still blow chunks, of course. @beartype gonna @beartype. But at least warning and exception messages emitted by @beartype no longer blow quite as much chunks. I'll take it.
Specifically:
Type-checking violations now sport a (slightly) more coherent colour scheme. Let me know if you hate it. Monochrome lovers gonna hate, of course. I (probably) won't do anything about your justifiable complaints, of course. I'm unresponsive, mentally flabby, and lack fortitude. I'll just quietly accept your abuse. But at least one of us might feel better.
The beartype.door.beartype_this_package() import hook (i.e., the rising child star of the @beartype ecosystem that our sketchy PR agency has been spamming your inbox with) now raises exception messages like this when called from:
Top-level scripts:
beartype.roar.BeartypeClawHookUnpackagedException: Top-level script
"/home/leycec/tmp/src/script.py" resides outside package structure.
Consider calling another "beartype.claw" import hook. However, note that only
other modules will be type-checked. "/home/leycec/tmp/src/script.py" itself
will remain unchecked. All business logic should reside in submodules
subsequently imported by "/home/leycec/tmp/src/script.py": e.g.,
# Instead of this at the top of "/home/leycec/tmp/src/script.py"...
from beartype.claw import beartype_this_package # <-- you are here
beartype_this_package() # <-- feels bad
# ...pass the basename of the "src/" subdirectory explicitly.
from beartype.claw import beartype_package # <-- you want to be here
beartype_package("src") # <-- feels good
from src.main_submodule import main_func # <-- still feels good
main_func() # <-- *GOOD*! "beartype.claw" type-checks this
some_global: str = 0xFEEDFACE # <-- *BAD*! "beartype.claw" ignores this
This has been a message from your friendly neighbourhood bear.
Top-level modules:
Top-level module "main.py" resides outside package structure but was
*NOT* directly run as a script. "beartype.claw" import hooks require
that modules either reside inside a package structure or be directly
run as scripts. Since neither applies here, you are now off the deep
end. @beartype no longer has any idea what is going on, sadly.
Consider directly decorating classes and functions by the
@beartype.beartype decorator instead: e.g.,
# Instead of this at the top of "main"...
from beartype.claw import beartype_this_package # <-- you are here
beartype_this_package() # <-- feels bad
# ...go old-school like it's 2017 and you just don't care.
from beartype import beartype # <-- you want to be here
@beartype # <-- feels good, yet kinda icky at same time
def spicy_func() -> str: ... # <-- *GOOD*! @beartype type-checks this
some_global: str = 0xFEEDFACE # <-- *BAD*! @beartype ignores this, but what can you do
For your safety, @beartype will now crash and burn.
Prefixes all warning messages with contextual metadata describing the origin of those warnings. This includes the names of the responsible module, class, and/or callables that are rapidly sapping your will to code even a single line more. Notably:
PEP 585 deprecations, in particular, were particularly useless. They failed to notify you where exactly the deprecated type hint came from. Now, @beartype candidly tells all about childhood trauma on the Christopher Robin farm:
from beartype import beartype
from typing import List # <-- deprecated is bad, but that doesn't mean you care
@beartype
def when_the_going_get_buggy(the_buggy_get_beartype: List[str]) -> None: ...
...which now raises a deprecation warning that actually helps you succeed on your own merit for once:
BeartypeDecorHintPep585DeprecationWarning: Function
__main__.when_the_going_get_buggy() parameter "the_buggy_get_beartype"
PEP 484 type hint typing.List[str] deprecated by PEP 585. This hint is
scheduled for removal in the first Python version released after October
5th, 2025. To resolve this, import this hint from "beartype.typing"
rather than "typing". For further commentary and alternatives, see also:
https://beartype.readthedocs.io/en/latest/api_roar/#pep-585-deprecations
PEP 526-compliant annotated variable assignments (e.g., muh_var: int | str = True), for which beartype.claw import hooks raised similarly useless type-checking violation messages. Thankfully:
Global annotated variable assignments like this:
bad_global: str = 0xFEEDFACE
...now yield violations like this:
beartype.roar.BeartypeDoorHintViolation: Global variable
"__main__.bad_global" value 4277009102 violates type hint <class
'str'>, as int 4277009102 not instance of str.
Local annotated variable assignments like this:
def bad_func():
bad_local: int = "This local is bad. It's bad. It knows it."
bad_func()
...now yield violations like this:
beartype.roar.BeartypeDoorHintViolation: Callable
paga.__main__.bad_func() local variable "bad_local" value "This local
is bad. It's bad. It knows it." violates type hint <class 'int'>, as
str "This local is bad. It's bad. It knows it." not instance of int.
Beartype 0.18.0: raise your paws in the air like you just don't care.
<sup>that feeling when you replace your hand with a black-and-white Ultima Cannon and it's still not good enough</sup>
Beartype 0.18.0 salutes the bear bros and gals and cats and rabid scrappy dogs that made this miracle possible:
@posita, @patrick-kidger, @wesselb, @tusharsadhwani, @JWCS, @iamrecursion, @rbroderi, @tvdboom, @AlanCoding, @crypdick,<sup>← lol</sup> @komodovaran, @rwiegan, @avolchek, @jaanli, @brettc, @spagdoon0411, @helderco, @jamesbraza, @dcharatan, @kasium, @uriyasama
<sup>Standard @beartype training exercise: all fun and games until you're down to the last chip.</sup>
Beartype 0.17.2 nervously skitters about on thin ice. Cracks form, yet beartype 0.17.2 fails to return to shore. "What are you even doing!?", the crow
Beartype 0.17.2 nervously skitters about on thin ice. Cracks form, yet beartype 0.17.2 fails to return to shore. "What are you even doing!?", the crowd exclaims. Verily, it is best not to ask questions:
pip install --upgrade beartype
This patch release comes courtesy these proud GitHub Sponsors, without whom @leycec's cats would currently be eating grasshoppers:
Thanks so much, masters of fintech.
Alright, alright. You found us out already.
Beartype 0.17.2 is an extremely minor patch release that exists purely to relax the bad assumption that all Python 3.9 releases unconditionally define the standard typing.ForwardRef.__forward_module__ dunder attribute, resolving issue #324 kindly submitted by stone-cold typonista @jvesely (Jan Vesely). Although Python ≥ 3.9.18 definitively defines this attribute, an unknown range of older Python 3.9 patch releases fail to do so.
Beartype 0.17.2 resolves this by naively pretending that all Python 3.9 releases fail to do so. Although kinda non-ideal, it's unclear whether this attribute is even used (i.e., set to a string) under Python 3.9. In fact, it's unclear whether this attribute is even used anywhere, ever. It probably will be under Python ≥ 3.13, but that's putting the proverbial cart before the horse. Anyyyyyyway.
We now return to your regularly scheduled Python hackathon.
Beartype 0.17.1 gently descends from the heavens on a golden dragon made of rainbows. "How can this be!?", the crowd exclaims. Verily, it is best not
Beartype 0.17.1 gently descends from the heavens on a golden dragon made of rainbows. "How can this be!?", the crowd exclaims. Verily, it is best not to ask questions:
pip install --upgrade beartype
This patch release comes courtesy these proud GitHub Sponsors, without whom @leycec's cats would currently be eating grasshoppers:
Thanks so much, masters of fintech.
This patch release adds explicit support for typing.NamedTuple subclasses under PEP 563 (i.e., from __future__ import annotations), resolving issue #318 kindly submitted by the cosmically rare-earth GitHub element @kasium. For unknown reasons (which probably reduce to "Guido was tired that day."), the typing.NamedTuple superclass exhibits high strangeness.
Specifically, for each typing.NamedTuple subclass named {MuhTuple}, the typing.NamedTuple superclass dynamically generates a {MuhTuple}.__new__() dunder method whose:
__annotations__ dunder attribute wraps all stringified type hints inside typing.ForwardRef(...) objects. Why? No reason.__module__ dunder attribute claims that method was defined in a fake module named named_{MuhTuple}. Why? Nobody knows.For example:
from __future__ import annotations # <-- PEP 563: it makes kittens cry
import typing
# When you said this...
class MuhTuple(typing.NamedTuple): # <-- very reasonable
muh_field: int # <-- makes sense, huh?
# ...what "typing.NamedTuple" heard you say was this:
class MuhTuple(typing.NamedTuple):
def __new__(cls, muh_field: ForwardRef('int')) -> None: # <-- wut
self.muh_field = muh_field
MuhTuple.__new__.__module__ = 'named_MuhTuple' # <-- lolbro
Why does typing.NamedTuple do these sad things? Because it is crazy. This is the official answer. Cray classes gonna cray.
@beartype now responds with a mountain of code that took us two weeks. Was that worth it? Probably not. Probably should have just implemented deep type-checking already. Instead, this is all we got.
@beartype 0.17.0 advised everybody to donate money to charitable causes. Instead, everybody donated more money to @beartype. Reverse psychology surely is the path of righteousness.
These monocled code aristocrats graciously filled the money trough, which the cats are now sleeping on against our wishes:
@DylanModesitt. @beartype now proudly markets you and everything you do. We're Team @DylanModesitt over here. Also, your GitHub Avatar is the boss. Feast your eyes, everybody!
<sup>the eyes follow my fingers as i type my password</sup>
@zhiyuanshi. Thanks to you, I have money. More importantly, I now know about spacemacs: Emacs + Vim key bindings. Urge... to... switch... IDEs... rising. My danger sense is tingling.
Lastly, @beartype thanks Bully Maguire for saving New York City with sassy hair, emo eye shadow, and impromptu cafe street dancing.
<sup>@beartype make a man feel like this, sometimes</sup>
One column per quarter.