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
7 years old
69 releases · first in 2020
Drag across the ruler to compare, or tap a release to open it.
@beartype 0.23.1 is the minor release that wishes it was the ultimate QA suplex. Instead, it just resolves a single regression at the intersection bet
@beartype 0.23.1 is the minor release that wishes it was the ultimate QA suplex. Instead, it just resolves a single regression at the intersection between @beartype 0.23.1, Python ≤ 3.13, and PEP 557-compliant @dataclasses.dataclass-decorated dataclasses defining one or more methods annotated by one or more PEP 484-compliant forward self-references (i.e., stringified forward references referring to the dataclass currently being defined). Ordinarily, @leycec would've uselessly sat on this issue resolution for nine months. Fortunately, he's done with ordinary – and so are you. The dog days are QA are over. The @beartype 0.23.0 release cycle changed the nature of @leycec. He now releases things so you don't have to:
# Via "pip", the once-great venerable master packager now fallen on hard times:
$ pip install --upgrade beartype # <-- you go, pipe-smoking pip
# Via "uv", the plucky upstart spiky-haired kid wielding a sword larger than its body:
$ uv pip install --upgrade beartype # <-- when you no longer have the strength to care about lock files
# Via "conda", the corporate scientist in casual lab attire who wants to be your buddy, pal:
$ conda config --add channels conda-forge # <-- where did python packaging go wrong?
$ conda install conda-forge::beartype # <-- it all seemed so simple, once.
<sup>Right: @beartype 0.23.1. Left: Your codebase. Middle: Your CTO stares dumbfounded.</sup>
@beartype 0.23.1 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>
...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:
@lukeocamden. Heroes among us.
Let us now admire a bipedal Latin tortoise.
<sup>your life after installing @beartype 0.23.1</sup>
Your coding agent can read these notes before it upgrades. Set up the MCP server →
@beartype 0.23.1 is the minor release that wishes it was the ultimate QA suplex. Instead, it just resolves a single regression at the intersection between @beartype 0.23.1, Python ≤ 3.13, and PEP 557-compliant @dataclasses.dataclass-decorated dataclasses defining one or more methods annotated by one or more PEP 484-compliant forward self-references (i.e., stringified forward references referring to the dataclass currently being defined). Ordinarily, @leycec would've uselessly sat on this issue resolution for nine months. Fortunately, he's done with ordinary – and so are you. The dog days are QA are over. The @beartype 0.23.0 release cycle changed the nature of @leycec. He now releases things so you don't have to:
# Via "pip", the once-great venerable master packager now fallen on hard times:
$ pip install --upgrade beartype # <-- you go, pipe-smoking pip
# Via "uv", the plucky upstart spiky-haired kid wielding a sword larger than its body:
$ uv pip install --upgrade beartype # <-- when you no longer have the strength to care about lock files
# Via "conda", the corporate scientist in casual lab attire who wants to be your buddy, pal:
$ conda config --add channels conda-forge # <-- where did python packaging go wrong?
$ conda install conda-forge::beartype # <-- it all seemed so simple, once.
Right: @beartype 0.23.1. Left: Your codebase. Middle: Your CTO stares dumbfounded.
@beartype 0.23.1 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.
The Masters of Fintech and Lifted Tides. That's who.
...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:
@lukeocamden. Heroes among us.
Let us now admire a bipedal Latin tortoise.
your life after installing @beartype 0.23.1
Follow breathtaking new @beartype announcements at @beartype's official Bluesky account ! I don't post often. I code often instead. Your feed will rem
Follow breathtaking new @beartype announcements at @beartype's official Bluesky account! I don't post often. I code often instead. Your feed will remain unpolluted and safe from cat memes... for now. I suddenly want to post lots of cat memes to Bluesky. Why is that? 🤔
Come live chat with all the @beartype homies at @beartype's official Zulip chat! Don't know how to type hint something? Unsure why @beartype is barfing all over logs? Heckle us in front of a live audience until we collapse or your team finally gets a straight answer. One of these two outcomes is likelier than the other. Zulip: it's like Discord... only less cool. A lot less cool. The UI and UX is frankly incomprehensible. At least Zulip is permissively Apache-licensed GitHub-hosted open-source. I'm not selling this whole Zulip thing, am I? 🥲
Come gape, gawk, and gander at @beartype's new official Zensical documentation:
beartype.github.io/beartype! The content may look exactly like @beartype's old unmaintained Sphinx documentation that we don't talk about anymore, but... uh, that's only because looks can be deceiving? Oh, alright. They're exactly the same. That will soon change. That had better soon change. Sphinx makes us "BARF!" like Larry in Rivercity Ransom. Zensical, on the other hand, is the delectable modern successor to Mkdocs. You do not want to know what happened to Mkdocs. Seriously. Don't go down that hole. Thanks so much to brilliant @beartype bro @posita for crushing this one out with his buddy "Claudio". 🤜 🤛
@beartype now routinely hits 4 million downloads a day. Apparently, that means something. Arbitrary numbers that get bigger matter to small petty bald men like me. It's like real-life suddenly became a hit JRPG – and I am so here for that energy. 😂
@beartype's GitHub Sponsors have collapsed into a black hole reading: "Nobody likes you, bro." @beartype basically doesn't have any sponsors anymore is what I'm saying. I blame no one but myself. I do the coding thing. I don't do the marketing thing. The results are unsurprising. Pity the Bear by feeding the Bear a dollar for a day. He may not learn to fish like that, but at least he'll be able to buy some fish for the cats. 🥹
@beartype
0.23.0rc0resolves so many mission-critical issues that everyone really wants to require @beartype0.23.0rc0as a minimum version in theirpyproject.tomlfiles. Save your app stack today before our last stable @beartype0.22.9release tears it down tomorrow. Just:
dependencies = [
...
"beartype >= 0.23.0rc", # <-- pretend @beartype 0.22.9 never existed. that's what we do.
...
]Protect your calls to
beartype_this_package()against malicious third-party import hooks. Call our new publicbeartype.claw.warn_if_beartype_claw_inactive()function to receive an informative non-fatal warning whenever somebody else stifles yourbeartype.clawimport hooks. If you'd like to dig even deeper into the contentious topic of import hooks that hate each other, consider @Glinte's third-partymetapathologypackage for all your investigatoryimportlibneeds. You tell 'em, @Glinte! Just:
from beartype.claw import beartype_this_package, warn_if_beartype_claw_inactive
beartype_this_package()
warn_if_beartype_claw_inactive() # <-- if the prior line did nothing, at least now you know :(Type-check NumPy, JAX, PyTorch, and CuPy tensor constraints with @acecchini's third-party
bearshapepackage! It's likejaxtyping, only @beartype-native from the ground-up. Likejaxtyping,bearshaperuntime type-checks tensors across a wide variety of frameworks. Unlikejaxtyping,bearshapecleanly integrates with @beartype.bearshapedoes not stomp all overbeartype.claw-based type-checking. You go,bearshape! Just:
from beartype import beartype
from bearshape import N, C
from bearshape.numpy import F32
@beartype
def normalize(x: F32[N, C]) -> F32[N, C]: # <-- i'm nodding like i understand this
return x / x.sum(axis=1, keepdims=True)Why are there so many crazy prefatory notes for this release, anyway? Everybody's already exhausted. This changelog hasn't even started yet, has it? 😮💨
<-- your face probably
@beartype 0.23.0rc0 thunders down the road of good QA intentions in a desperate bid to crush all the skittering bugs eating your codebase to the bone. Under its spike-studded wheels of doom stability, @beartype 0.23.0rc0 exposes the fragile arrogance at the heart of trying to do anything crush bugs in Python:
# Via "pip", the once-great venerable master packager now fallen on hard times:
$ pip install --upgrade beartype # <-- you go, pipe-smoking pip
# Via "uv", the plucky upstart spiky-haired kid wielding a sword larger than its body:
$ uv pip install --upgrade beartype # <-- when you no longer have the strength to care about lock files
# Via "conda", the corporate scientist in casual lab attire who wants to be your buddy, pal:
$ conda config --add channels conda-forge # <-- where did python packaging go wrong?
$ conda install conda-forge::beartype # <-- it all seemed so simple, once.
Right: @beartype 0.23.0rc0. Left: Your codebase. Middle: Your CTO stares dumbfounded.
@beartype 0.23.0rc0 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.
The Masters of Fintech and Lifted Tides. That's who.
@beartype 0.23.0rc0 had to get out tonight. Python was at stake. QA, which is always quietly on fire, would've caught on even more fire. Therefore, this changelog sucks even more than it would've on a good Friday. It's a tiny fragment of what @beartype 0.23.0rc0 is capable of. But that's fine. Because, ultimately, what @beartype 0.23.0rc0 is capable of is not destroying your codebase.
Sometimes, not destroying your codebase is all that matters. 👍
@beartype 0.23.0rc0: when two ugly pancakes with arms collide, a QA baby is born
warn_if_beartype_claw_inactive(): You Seriously Wanna Call This FunctionPython's burgeoning import hook ecosystem has basically broken down. It never worked all that well to begin with. Now, it increasingly doesn't work at all. First, the bad news, bears. The tl;dr is this:
beartype.claw import hooks are silently ignored whenever a PyInstaller, jaxtyping, or typeguard import hook is used anywhere in the current Python process.Yeah. We know. This isn't just rough. This is abrasively cataclysmic. Let's talk about why this is happening.
Currently, beartype.claw import hooks may be silently overridden and thus disabled under various common conditions. When this occurs, @beartype will silently fail to apply beartype.claw-based runtime type-checking to affected third-party packages and modules. This means your packages and modules, because you are reading this and now frowning. Python app stacks affected by this include any that either:
beartype.claw. Not much we can do about that. Please complain to PyInstaller itself. Openly weep like this to make them feel bad: 😭jaxtyping. If you currently use jaxtyping import hooks, consider switching to @acecchini's third-party bearshape package. bearshape cleanly integrates with @beartype, supports basically everything jaxtyping supports, and even comes with a more Pythonic syntax that looks suspiciously (but welcomely) like standard typing type hint syntax. 👏 👋 👏typeguard. If you currently also use typeguard import hooks, I have no good advice at the moment. "Please seriously don't do that," is the best I can offer at the moment. @beartype 0.24.0 will fix these incompatibilities once and for all. Until then, @beartype weeps for Python's broken import hook ecosystem. 😿That's the bad news. This is happening because Python lacks standards governing interoperability between competing third-party import hooks. No new standards that could remedy this situation appear to be forthcoming in the near future, either. No one cares that Python's import hook ecosystem doesn't work at the moment. Kinda sad.
The good news is that @beartype can resolve most of this situation entirely on its own. A future version of @beartype will do just that. Probably @beartype 0.24.0 in a few months, because this ongoing contention between import hooks is awful. It has to stop. Thus, we are forcing it to stop. Our way. The @beartype way. 💪 🐻
The bad bad news is that @beartype isn't doing that at the moment. Until @beartype resolves import hook contention on its side, consider manually calling our new public beartype.claw.warn_if_beartype_claw_inactive() function after calling any beartype.claw import hook (e.g., beartype_this_package()). If somebody else stifled that call without your consent, you'll receive an informative non-fatal warning that could destroy your will to continue coding:
from beartype.claw import beartype_this_package, warn_if_beartype_claw_inactive
beartype_this_package()
warn_if_beartype_claw_inactive() # <-- if the prior line did nothing, at least now you know :(See also this feature request for a horrifyingly detailed description of a new pseudostandard I just made up to force cooperation between competing third-party import hooks. When you want to feel deranged, you want to read that issue. 😆 <-- not that funny honestly
If you'd like to dig even deeper into the contentious topic of import hooks that hate each other, consider @Glinte's third-party metapathology package for all your investigatory importlib needs. You tell 'em, @Glinte! ✊
when your right arm refuses to put itself down, you know you should've upgraded to @beartype 0.23.0rc0
BeartypeConf(is_random=False): Never Do This and No One Gets HurtSo. You want to disable @beartype's default pseudorandom type-checking behaviour, huh? You think you want many things in life – until you finally get what you asked for. Then the monkey's pawl curls. Your codebase dies quietly. You shriek to an uncaring city skyline shortly before the burning helicopter hurtles to the ground:
"Why? Why is this happening!?"
@beartype's default pseudorandom type-checking behaviour is a good thing. You forgot that essential lesson in life. Pseudorandom type-checking dramatically increases the likelihood of catching invalid items in pure-Python containers (e.g., dict, list) before they have a chance to hurtle burning helicopters to the ground.
Sometimes, though, that default behaviour is not a good thing. There is a valid reason for disabling pseudorandom type-checking: test consistency. Want tests to fail consistently, uniformly, and deterministically rather than dissolving into a non-deterministic crapshoot of incoherent fragility? It happens. We understand. Then your tests want to explicitly disable the new BeartypeConf(is_random=False) configuration option as follows:
# In some pytest-driven unit test somewhere that currently hates @beartype...
def test_beartype_haters_gonna_hate() -> None:
from beartype import beartype, BeartypeConf
# Test-specific @beartype decorator performing deterministic type-checking! Ugh.
boring_beartype = beartype(conf=BeartypeConf(is_random=False))
@boring_beartype
def beartype_randomness(can_suck_an_egg: list[str]) -> str:
return can_suck_an_egg[0]
# This assertion is now guaranteed to *ALWAYS* succeed, despite the fact that
# this call semantically violates the type hint annotating the "can_suck_an_egg"
# parameter accepted by the beartype_randomness() function defined above. But
# you don't care anymore, do you? You just want this to pass. Now, it can.
#
# The only cost is sanity. Because nothing means anything anymore. Enjoy.
kinda_awful_honestly = beartype_randomness([
'A string, yo.', b'...totally not a string', 0xFEEDBABE])
assert kinda_awful_honestly == 'A string, yo.'Sure. It's awful. Sometimes, that's exactly what you need.
BeartypeConf(is_random=False): when you need awful, you need @beartype.
@beartype 0.23.0rc0: "your single new configuration option fails to impress me"
OHNOES. It's 2:13AM. An ominous time, if ever there was. I've gotta wrap this thing up quickly while convincing you that I intensely care about this concluding section.
Here's the deal. Forward references? You know, those type hints that are strings referring to an external type or type hint defined somewhere else that you can't import into the current module for specious reasons that are better left undocumented? Those forward references?
...yeah. Prior versions of @beartype only pretended to support forward references. @beartype's previous support for forward references was so slipshod, unreliable, and context-dependent that @beartype basically didn't support forward references. Not really, anyway.
That's why I spent the last six months why is life like this completely rewriting @beartype's internal forward reference resolution engine from the ground up. Common uses cases that now reliably work include:
Forward references to arbitrary type hints defined elsewhere. Previously, @beartype only supported forward references to classes. Now, @beartype's supports forward references to literally anything. If it's a valid type hint, you can now refer to it: e.g.,
# In submodule "i_pity.da_foo":
WorstTypeHintEver = 'list[int]' # <-- look i don't know it's late
# In submodule "i_pity.da_bar":
from beartype import beartype
@beartype
def pitiable_func(grovelling_arg: 'i_pity.da_foo.WorstTypeHintEver') -> int:
return grovelling_arg[0]
pitiable_func([0xBABEFACE]) # <-- uh wutRelative forward references in die_if_unbearable() and is_bearable() calls. Previously, both the die_if_unbearable() and is_bearable() functions prohibited relative forward references (i.e., forward references omitting a module name and thus relative to the current module). Now, die_if_unbearable() and is_bearable() dynamically hunt up the call stack for the calling module calling those functions and intelligently resolve relative forward references against that calling module: e.g.,
from beartype.door import die_if_unbearable
def its_so_late(my_face_is_gonna_fall_off: object) -> None:
die_if_unbearable(
my_face_is_gonna_fall_off,
'SomeClassThatHasntBeenDefinedYet' # <-- relative forward reference! so cool
)
class SomeClassThatHasntBeenDefinedYet: ...
# This totally works now. Yay! What a lame example, though. Can we all agree this
# example was lame? We can. I don't mind someone rubbing that the truth into my soul.
its_so_late(SomeClassThatHasntBeenDefinedYet())Heaps of other forward reference stuff, too. It's late. We're done.
Peace out, wonderful bear family! We'll excrete a heap more text that actually means something for the official stable @beartype 0.23.0 mic drop. Until then, have a wonderful remainder of your summer – and may the QA be with you always. 🫶 🥰 💞
Robot Chicken says: "OMG @beartype 0.23.0rc0! PEACE OUT Y'ALL! I'M A ROBOT CHICKEN!!!!"
Almost forgot. @beartype 0.23.0rc0 also officially supports Python 3.15. That's right, y'all. As of @beartype 0.23.0rc0, Robot Chicken ain't the only one who can use the word "y'all" anymore, y'all.
Python 3.15: "You want the JIT speed it bringin'."
@beartype 0.23.0rc0: when it cross its arms, you just know all bugs is dead
...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. @Glinte. @wesselb. @jorenham. @JWCS. @adamtheturtle. @tusharsadhwani. @TeamSpen210. @bitranox. @ilyapoz. @benoit74. @hmgaudecker. @nstarman. @Gattocrucco. @javi-linx. @tseaver. @kdeldycke. @gotmax23. @black-snow. @DetachHead. @asitstands. @jeertmans. @abhinand-c. @mzealey. @ITcarrot. @danielkovtun. @ddorian. @riesentoaster. @sean-roelofs-ai. Heroes among us.
@beartype 0.23.X dev cycle: still accursed after all these cat memes.
@beartype 0.23.0 welcomes you in a warm (yet unyielding) bear hug. It crushes the air out of your lungs and the bugs scuttling through the codebase. All aboard. Calling all QA! The unsubstantiated hype train starts here:
@beartype
0.23.0resolves so many mission-critical issues that everyone really wants to require @beartype0.23.0as a minimum version in theirpyproject.tomlfiles. Save your app stack today before our last stable @beartype0.22.9release tears it down tomorrow. Just:
dependencies = [
...
"beartype >= 0.23.0", # <-- pretend @beartype 0.22.9 never existed. that's what we do.
...
]
<sup>@beartype 0.22.9: the arthritic fat cat in the room brandishes a paw hook you no longer trust</sup>
To best introduce @beartype 0.23.0, we now talk about everything except @beartype 0.23.0:
Follow breathtaking new @beartype announcements at @beartype's official Bluesky account! I don't post often. I code often instead. Your feed will remain unpolluted and safe from cat memes... for now. I suddenly want to post lots of cat memes to Bluesky. Why is that? :thinking:
Come live chat with all the @beartype homies at @beartype's official Zulip chat! Don't know how to type hint something? Unsure why @beartype is barfing all over logs? Heckle us in front of a live audience until we collapse or your team finally gets a straight answer. One of these two outcomes is likelier than the other. Zulip: it's like Discord... only less cool. A lot less cool. The UI and UX is frankly incomprehensible. At least Zulip is permissively Apache-licensed GitHub-hosted open-source. I'm not selling this whole Zulip thing, am I? :smiling_face_with_tear:
Come gape, gawk, and gander at @beartype's new official Zensical documentation:
beartype.github.io/beartype! The content may look exactly like @beartype's old unmaintained Sphinx documentation that we don't talk about anymore, but... uh, that's only because looks can be deceiving? Oh, alright. They're exactly the same. That will soon change. That had better soon change. Sphinx makes us "BARF!" like Larry in Rivercity Ransom. Zensical, on the other hand, is the delectable modern successor to Mkdocs. You do not want to know what happened to Mkdocs. Seriously. Don't go down that hole. Thanks so much to brilliant @beartype bro @posita for crushing this one out with his buddy "Claudio". :fist_right: :fist_left:
@beartype now routinely hits
43 million downloads a day. Apparently, that means something. Arbitrary numbers that get bigger matter to small petty bald men like me. It's like real-life suddenly became a hit JRPG – and I am so here for that energy. :joy: UPDATE: 3 million downloads a day is still good! Right, guys? Right... That's still millions, technically. Same order of magnitude. Just a little bit shift to the right. You know, maybe it's best to round up to the nearest 10 million. Sounds reasonable, you know? Small petty bald men like me base their entire emotional state and inner monologue on exogenous authority figures like PyPIStats. I stop typing. :sob:
Protect your calls to
beartype_this_package()against malicious third-party import hooks. Call our new publicbeartype.claw.warn_if_beartype_claw_inactive()function to receive an informative non-fatal warning whenever somebody else stifles yourbeartype.clawimport hooks. If you'd like to dig even deeper into the contentious topic of import hooks that hate each other, consider @Glinte's third-partymetapathologypackage for all your investigatoryimportlibneeds. You tell 'em, @Glinte! Just:
from beartype.claw import beartype_this_package, warn_if_beartype_claw_inactive
beartype_this_package()
warn_if_beartype_claw_inactive() # <-- if the prior line did nothing, at least now you know :(
Type-check
pytestfixtures and tests with our very own first-partypytest-beartypeplugin! No otherpytestplugin goes so far, because otherpytestplugins value their maintainer's sanity. Ours doesn't. You go,pytest-beartype! Just:
pytest --beartype-tests --beartype-test-fixtures --beartype-packages="muh_package" # <-- crush 'em
Type-check NumPy, JAX, PyTorch, and CuPy tensor constraints with @acecchini's third-party
bearshapepackage! It's likejaxtyping, only @beartype-native from the ground-up. Likejaxtyping,bearshapetype-checks tensors across popular competing tensor frameworks. Unlikejaxtyping,bearshapecleanly integrates with @beartype – preserving bothbeartype.clawimport hooks andBeartypeConfconfigurations. You go,bearshape! Just:
from beartype import beartype
from bearshape import N, C
from bearshape.numpy import F32
@beartype
def normalize(x: F32[N, C]) -> F32[N, C]: # <-- i'm nodding like i understand this
return x / x.sum(axis=1, keepdims=True)
Why are there so many crazy prefatory notes for this release, anyway? Everybody's already exhausted. This changelog hasn't even started yet, has it? :face_exhaling:
<-- your face probably
<sup>average family pet is badly dubbed after installing @beartype 0.23.0</sup>
0.23.0: The Changelog <sup>...is almost about to begin, but this isn't it</sup>@beartype 0.23.0 thunders down the road of good QA intentions in a desperate bid to crush all the skittering bugs eating your codebase to the bone. Under its spike-studded wheels of doom stability, @beartype 0.23.0 exposes the fragile arrogance at the heart of trying to do anything crush bugs in Python:
# Via "pip", the once-great venerable master packager now fallen on hard times:
$ pip install --upgrade beartype # <-- you go, pipe-smoking pip
# Via "uv", the plucky upstart spiky-haired kid wielding a sword larger than its body:
$ uv pip install --upgrade beartype # <-- when you no longer have the strength to care about lock files
# Via "conda", the corporate scientist in casual lab attire who wants to be your buddy, pal:
$ conda config --add channels conda-forge # <-- where did python packaging go wrong?
$ conda install conda-forge::beartype # <-- it all seemed so simple, once.
<sup>Right: @beartype 0.23.0. Left: Your codebase. Middle: Your CTO stares dumbfounded.</sup>
@beartype 0.23.0 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>
0.23.0: The Changelog <sup>subtitle: "by their bugs you shall crush them"</sup>@beartype 0.23.0 brings the Halloween goodie grab bag of QA sweets carefully handcrafted by Italian monkey-cats to destroy your tooth enamel and gums destroy all the bugs with big guns running amok in your git branches:
Python 3.15! Coincidentally, Python 3.15 was released today a few days ago. Surely, this last-ditch @beartype 0.23.0 care package that frankly isn't ready has nothing to do with Python 3.15 dropping... surely. The adverb "surely" surely doesn't mean much anymore. What's an adverb, anyway? No idea. I blast bugs for an open-source "living." Bugs skittle. I blast. Grammar, spelling, and punctuation are scope creep. I stop typing. :hot_face:
Import hook contention detection! Import hook contention got your codebase down – literally? Unsure whether beartype.claw import hooks like beartype_this_package() are even doing anything anymore? Do you suspect that the sketchy bald package named sketchy_bald_package the cocky LLM berated you into installing last night is doing Double Plus Ungood Stuff™ – like silently reducing beartype.claw import hooks to an unproductive noop? Did that sketchy bald coworker sabotage your QA workflow yet again? When the bugs crawl, who you gonna call?
beartype.claw.warn_if_beartype_claw_inactive() function after calling any beartype.claw import hook. If somebody else stifled our import hooks without your consent, you'll receive an informative non-fatal warning that could destroy your will to continue coding. Because the end users you adore from beartype.claw import beartype_this_package, warn_if_beartype_claw_inactive
beartype_this_package()
warn_if_beartype_claw_inactive() # <-- if the prior line did nothing, at least now you know :(
BeartypeConf(is_random=False). Force @beartype to type-check pure-Python containers (e.g., dict, list) deterministically rather than pseudo-randomly. Great for testing, because determinism is the friendly bedfellow of passing tests. Awful for production code (and everything else), because pseudo-random walks over container items type-check reality better than deterministically type-checking only the first item of every container, which is what this does. Determinism is a niche. It's like avante garde French cinema with suspicious titles like "Liolioli." You know exactly what you're getting – and that's the problem:
# In some pytest-driven unit test somewhere that currently hates @beartype...
def test_beartype_haters_gonna_hate() -> None:
from beartype import beartype, BeartypeConf
from random import randrange
# Custom @beartype decorator forcing deterministic type-checking. *UGH*.
boring_beartype = beartype(conf=BeartypeConf(is_random=False))
@boring_beartype
def beartype_randomness(can_suck_an_egg: list[str]) -> str:
return can_suck_an_egg[randrange(0, len(can_suck_an_egg))]
# This assertion is now guaranteed to *ALWAYS* succeed, despite the fact that
# this call semantically violates the type hint annotating the "can_suck_an_egg"
# parameter accepted by the beartype_randomness() function defined above. But
# you don't care anymore, do you? You just want this to pass. Now, it can.
#
# The only cost is sanity. Because nothing means anything anymore. Enjoy.
kinda_awful_honestly = beartype_randomness([
'A string, yo.', b'...totally not a string', 0xFEEDBABE])
assert kinda_awful_honestly == 'A string, yo.'
typing.Never. @beartype 0.23.0 now transparently supports the PEP-noncompliant (albeit increasingly popular) typing.Never type hint singleton, semantically equivalent to the PEP 484-compliant typing.NoReturn type hint singleton. Why? Just 'cause, really. @Glinte wanted this years ago. What @Glinte wants, @Glinte gets. Feed @Glinte for a day release and he will QA for a lifetime all future releases: e.g.,
from beartype import beartype
from typing import Never, NoReturn
@beartype
def fatty_qa_diet() -> NoReturn: # <-- good. this is good.
raise ValueError()
@beartype
def low_qa_bar() -> Never: # <-- seriously, python? we seriously doing typing synonyms now?
raise ValueError()
@warnings.deprecated. @beartype 0.23.0 now supports both the PEP 702-compliant @warnings.deprecated decorator and its @typing_extensions.deprecated backport, trivializing deprecation warnings throughout your codebase. This feature is so intrinsically exciting, not even 70's throwback lyrics can save it:
from beartype import beartype
from collections.abc import Generator
from contextlib import contextmanager
from warnings import deprecated
@beartype
@deprecated("They stab it") # <-- why? why do they stab it, though!?
@contextmanager
def their_steely_knives() -> Generator: # <- 2 legit 2 QA
yield
with their_steely_knives(): # <- prints "DeprecationWarning: They stab it".
print("But they just can't kill the beast") # look i don't know either.
Official thread-safety. @beartype is now officially thread-safe. You always thought it was. We don't talk about the past here. Instead, we valiantly claim with some evidence that @beartype ≥ 0.23.0 is now safe for use under free-threaded CPython ≥ 3.13 builds. Our quality assurance is your down payment on... uh, something you want. Wow. That once-promising one-liner sure ended tragically, didn't it? :hot_face:
threading.{Lock,RLock}. @beartype 0.23.0 now accepts the mostly PEP-noncompliant threading.Lock and threading.RLock attributes as valid type hints:
from beartype import beartype
from dataclasses import dataclass
from threading import Lock, RLock
@beartype
@dataclass
class Config:
muh_lock: Lock # <---- @beartype no longer hates the existence of this.
muh_rlock: RLock # <-- @beartype also accepts that this exists without hatred.
Forward references. Previously, @beartype's internal forward reference resolution engine was better than nothing, despite nothing being what you usually got out of it. Now, @beartype's internal forward reference resolution engine actually does something. It does a lot of things. Actually, it's super-insane. It's annotationlib on nootropics an all-night Halloween bender at the local 80's-themed arcade vape parlor. It's that good. Specifically, @beartype now supports:
Forward references to arbitrary type hints defined elsewhere. Previously, @beartype only supported forward references to classes. Now, @beartype's supports forward references to literally anything. If it's a valid type hint, you can now refer to it: e.g.,
# In submodule "i_pity.da_foo":
WorstTypeHintEver = 'list[int]' # <-- look i don't know it's late
# In submodule "i_pity.da_bar":
from beartype import beartype
@beartype
def pitiable_func(grovelling_arg: 'i_pity.da_foo.WorstTypeHintEver') -> int:
return grovelling_arg[0]
pitiable_func([0xBABEFACE]) # <-- uh wut
Relative forward references in die_if_unbearable() and is_bearable() calls. Previously, both the die_if_unbearable() and is_bearable() functions prohibited relative forward references (i.e., forward references omitting a module name and thus relative to the current module). Now, die_if_unbearable() and is_bearable() dynamically hunt up the call stack for the calling module calling those functions and intelligently resolve relative forward references against that calling module: e.g.,
from beartype.door import die_if_unbearable
def its_so_late(my_face_is_gonna_fall_off: object) -> None:
die_if_unbearable(
my_face_is_gonna_fall_off,
'SomeClassThatHasntBeenDefinedYet' # <-- relative forward reference! so cool
)
class SomeClassThatHasntBeenDefinedYet: ...
# This totally works now. Yay! What a lame example, though. Can we all agree this
# example was lame? We can. I don't mind someone rubbing that the truth into my soul.
its_so_late(SomeClassThatHasntBeenDefinedYet())
open(..., encoding='*') < typing.TextIO == typing.IO[str] and io.FileIO(...) == open(..., '*b') < typing.BinaryIO == typing.IO[bytes]. Previously, file handles were not reliably type-checkable at runtime. Now, @beartype type-checks both text and binary file handles against standard IO type hints:
from beartype.door import is_bearable, is_subhint # <-- all your QA base
from io import BytesIO, FileIO, StringIO # <-- non-standard weird stuff
from typing import IO, BinaryIO, TextIO # <-- standard type hints
# @beartype 0.23.0 now type-checks isinstance() relations between file handles
# and IO type hints. Raise up your hands in the universal sign of exhaustion.
assert is_bearable(open('/dev/null', 'rb'), IO[bytes]) is True # <-- binary file is binary: *GUD*
assert is_bearable(FileIO('/dev/null', 'rb'), BinaryIO) is True # <- binary file is binary: *GUD*
assert is_bearable(open('/dev/null', 'r'), IO[str]) is True # <----- text file is text: *GUD*
assert is_bearable(FileIO('/dev/null', 'r'), TextIO) is False # <--- text file is... not text!? oh well
assert is_bearable(BytesIO(), BinaryIO) is False # <---------------- binary buffer is... not binary!? sad
assert is_bearable(StringIO(), TextIO) is False # <----------------- string buffer is... not text!? sosad
# @beartype 0.23.0 now type-checks issubclass() relations between IO type hints,
# too. Prove the hideous truth that the world may now see.
assert is_bearable(FileIO, type[BinaryIO]) is True # <---- io.FileIO is binary IO protocol: *SURE*
assert is_bearable(FileIO, type[TextIO]) is False # <----- io.FileIO is text IO protocol: ...no? okay, then
assert is_bearable(BinaryIO, type[IO[bytes]]) is True # <- typing.BinaryIO is binary IO protocol: *YUP*
assert is_bearable(TextIO, type[IO[str]]) is True # <----- typing.TextIO is text IO protocol: *YUP*
assert is_bearable(BytesIO, type[BinaryIO]) is False # <-- io.BytesIO is binary IO protocol: ...no? we sigh
Generics parametrized by parameter specifications and one or more other arbitrary child type hints. @beartype 0.23.0 now supports user-defined PEP 484- or 585-compliant generics (e.g., typing.Generic subclasses) and PEP 544-compliant protocols (i.e., typing.Protocol subclasses) parametrized by PEP 612-compliant parameter specifications (i.e., typing.ParamSpec objects) followed by one or more other arbitrary child type hints. No one read this far. No one. @beartype will post a meme of a cat wearing a sailor outfit should the prior two sentences prove false. But they won't. That's how depressingly boring this feature is:
from beartype import beartype
from typing import Generic, ParamSpec, TypeVar
P = ParamSpec('P')
R = TypeVar('R')
class Gen(Generic[P, R]): ...
@beartype
def so_generic_so_boring() -> Gen[P, S]: # <-- nobody knows what this means. nobody.
return Gen()
so_generic_so_boring() # <-- descriptive name is proscriptive. what that even mean!?
tuple[..., typing.Unpack[tuple[...]]. @beartype 0.23.0 now supports sugar-free backward-compatible tuple type hint unpacking of the form tuple[..., typing.Unpack[tuple[...]] standardized by PEP 646 – the only typing standard that exhausts bald men so fully they give up partway before risking further hair loss:
from beartype import beartype
from typing import Unpack
@beartype
def muh_func_no_idea_bro(x: int) -> (
tuple[int, Unpack[tuple[int, ...]]]): # <-- what the... what does this even mean!?
ls = [i for i in range(x)]
return x, *ls
muh_func_no_idea_bro(5) # <-- i accept things i don't understand
type[typing.Annotated[cls, ...]]. @beartype 0.23.0 now supports PEP 484- and 585-compliant type[...] subclass type hints subscripted by PEP 593-compliant Annotated[cls, ...] child type hints subscripted by... uh, classes. Who even does stuff like this!? Oh, right. NumPy pymaster @jorenham (Joren Hammudoglu). Dude's right about everything. If it's for NumPy, it can't be wrong:
from beartype.door import die_if_unbearable
from beartype.vale import Is
from typing import Annotated
# My eyes may be bleeding, but they bleed for NumPy. It's for data science.
# The eyes are a small sacrifice, Boo.
die_if_unbearable(
str, # <-- this is easy. i get this.
type[Annotated[str, Is[lambda text: len(text) > 30]]], # <-- ...uh...
)
Third-party stuff. @beartype supports even more hawt third-party jibberish that I barely understand, including:
coverage command and package that fuels QA everywhere! Previously, Coverage.py and beartype.claw import hooks hated each other. Now, they don't. BFFL status has been restored. CI friends are the best friends. Incidentally, this was pure Hell to get working. You know the kind of Hell. That kind. There are a billion metal bands and albums named "Hell." We've all listened to every single one. Still didn't help. Coverage.py hating beartype.claw took months to resolve. Even when I thought I'd resolved it, I still hadn't. Hell: "When Coverage.py beats beartype.claw up on the way to the water cooler." :people_hugging:markdown-exec! Executable code in Markdown blocks, huh? Nothing could possibly go wrong here. :face_holding_back_tears:conf.py scripts. We do not talk about Sphinx here. <sup><-- you get no emoji, sphinx</sup>numpy.typing.NDArray[...] type hints were refactored from PEP 484-compliant generics into PEP 695-compliant type aliases. That means something. Possibly even to me.
<sup>@beartype 0.23.0: brought to you by the only catgirl meme suitable for work</sup>
@beartype 0.23.0 is the heroic byproduct of open-source volunteerism. For the first time, people and people-like LLMs who are not me did something. They did a lot of something. All prior releases were pretty much the one-bald-man @leycec show. :face_exhaling:
With @beartype 0.23.0, that's begun changing. Finally. Praise be to Anthropic and OpenAI for they have released me from QA bondage. Sounds weird when I put it like that... Maybe I shouldn't put it like that. Oh, well. Too late. We're running with this uncensored changelog as is! No edits. Only half-truths, rictus grins, and nail-biting anxiety.
@beartype 0.23.0 would not be here without:
beartype.door.TypeHint API. beartype.door.TypeHint is the backbone for both Plum-based multiple dispatch and @beartype's own public is_subhint() tester. Stabilizing TypeHint thus stabilizes both Plum and @beartype itself. Thank you a metric tensor, @nstarman! Your sacrifice is a noble example to us all. The human propensity for masochism is legendary throughout the multiverse. @nstarman's came at a cost. A cost @beartype was willing to pay. :joy:pytest-beartype. pytest-beartype matters to... uh, 25 people, huh? 25 people out of 9 billion, huh? That's statistics for you. It was hard to make humans care about a QA tool stacked on a QA tool, but 25 humans managed. We salute The High 25. Thank you a starry-eyed emoji, @adamtheturtle! You demolished your sanity for us all. :star_struck:
<sup>@beartype 0.23.0: when you want to beat a bed while crying, think of them</sup>
@beartype 0.23.0 had to get out tonight. Python was at stake. QA, which is always quietly on fire, would've caught on even more fire. Therefore, this changelog sucks even more than it would've on a good Friday. It's a tiny fragment of what @beartype 0.23.0 is capable of. But that's fine. Because, ultimately, what @beartype 0.23.0 is capable of is not destroying your codebase.
Sometimes, not destroying your codebase is all that matters. :+1:
<sup>@beartype 0.23.0: when two ugly pancakes with arms collide, a QA baby is born</sup>
warn_if_beartype_claw_inactive(): You Seriously Wanna Call This FunctionPython's burgeoning import hook ecosystem has basically broken down. It never worked all that well to begin with. Now, it increasingly doesn't work at all. First, the bad news, bears. The tl;dr is this:
beartype.claw import hooks are silently ignored whenever a PyInstaller, jaxtyping, or typeguard import hook is used anywhere in the current Python process.Yeah. We know. This isn't just rough. This is abrasively cataclysmic. Let's talk about why this is happening.
Currently, beartype.claw import hooks may be silently overridden and thus disabled under various common conditions. When this occurs, @beartype will silently fail to apply beartype.claw-based runtime type-checking to affected third-party packages and modules. This means your packages and modules, because you are reading this and now frowning. Python app stacks affected by this include any that either:
beartype.claw. Not much we can do about that. Please complain to PyInstaller itself. Openly weep like this to make them feel bad: :sob:jaxtyping. If you currently use jaxtyping import hooks, consider switching to @acecchini's third-party bearshape package. bearshape cleanly integrates with @beartype, supports basically everything jaxtyping supports, and even comes with a more Pythonic syntax that looks suspiciously (but welcomely) like standard typing type hint syntax. :clap: :wave: :clap:typeguard. If you currently also use typeguard import hooks, I have no good advice at the moment. "Please seriously don't do that," is the best I can offer at the moment. @beartype 0.24.0 will fix these incompatibilities once and for all. Until then, @beartype weeps for Python's broken import hook ecosystem. :crying_cat_face:That's the bad news. This is happening because Python lacks standards governing interoperability between competing third-party import hooks. No new standards that could remedy this situation appear to be forthcoming in the near future, either. No one cares that Python's import hook ecosystem doesn't work at the moment. Kinda sad.
The good news is that @beartype can resolve most of this situation entirely on its own. A future version of @beartype will do just that. Probably @beartype 0.24.0 in a few months, because this ongoing contention between import hooks is awful. It has to stop. Thus, we are forcing it to stop. Our way. The @beartype way. :muscle: :bear:
The bad bad news is that @beartype isn't doing that at the moment. Until @beartype resolves import hook contention on its side, consider manually calling our new public beartype.claw.warn_if_beartype_claw_inactive() function after calling any beartype.claw import hook (e.g., beartype_this_package()). If somebody else stifled that call without your consent, you'll receive an informative non-fatal warning that could destroy your will to continue coding:
from beartype.claw import beartype_this_package, warn_if_beartype_claw_inactive
beartype_this_package()
warn_if_beartype_claw_inactive() # <-- if the prior line did nothing, at least now you know :(
See also this feature request for a horrifyingly detailed description of a new pseudostandard I just made up to force cooperation between competing third-party import hooks. When you want to feel deranged, you want to read that issue. :laughing: <sup><-- not that funny honestly</sup>
If you'd like to dig even deeper into the contentious topic of import hooks that hate each other, consider @Glinte's third-party metapathology package for all your investigatory importlib needs. You tell 'em, @Glinte! :fist_raised:
<sup>when your right arm refuses to put itself down, you know you should've upgraded to @beartype 0.23.0</sup>
<sup>also, are those... uh, mushrooms on that yellow dude's head? @beartype 0.23.0 is just as stunned</sup>
BeartypeConf(is_random=False): Never Do This and No One Gets HurtSo. You want to disable @beartype's default pseudorandom type-checking behaviour, huh? You think you want many things in life – until you finally get what you asked for. Then the monkey's pawl curls. Your codebase dies quietly. You shriek to an uncaring city skyline shortly before the burning helicopter hurtles to the ground:
"Why? Why is this happening!?"
@beartype's default pseudorandom type-checking behaviour is a good thing. You forgot that essential lesson in life. Pseudorandom type-checking dramatically increases the likelihood of catching invalid items in pure-Python containers (e.g., dict, list) before they have a chance to hurtle burning helicopters to the ground.
Sometimes, though, that default behaviour is not a good thing. There is a valid reason for disabling pseudorandom type-checking: test consistency. Want tests to fail consistently, uniformly, and deterministically rather than dissolving into a non-deterministic crapshoot of incoherent fragility? It happens. We understand. Then your tests want to explicitly disable the new BeartypeConf(is_random=False) configuration option as follows:
# In some pytest-driven unit test somewhere that currently hates @beartype...
def test_beartype_haters_gonna_hate() -> None:
from beartype import beartype, BeartypeConf
from random import randrange
# Custom @beartype decorator forcing deterministic type-checking. *UGH*.
boring_beartype = beartype(conf=BeartypeConf(is_random=False))
@boring_beartype
def beartype_randomness(can_suck_an_egg: list[str]) -> str:
return can_suck_an_egg[randrange(0, len(can_suck_an_egg))]
# This assertion is now guaranteed to *ALWAYS* succeed, despite the fact that
# this call semantically violates the type hint annotating the "can_suck_an_egg"
# parameter accepted by the beartype_randomness() function defined above. But
# you don't care anymore, do you? You just want this to pass. Now, it can.
#
# The only cost is sanity. Because nothing means anything anymore. Enjoy.
kinda_awful_honestly = beartype_randomness([
'A string, yo.', b'...totally not a string', 0xFEEDBABE])
assert kinda_awful_honestly == 'A string, yo.'
Sure. It's awful. Sometimes, that's exactly what you need.
BeartypeConf(is_random=False): when you need awful, you need @beartype.
<sup>@beartype 0.23.0: "your single new configuration option fails to impress me"</sup>
OHNOES. It's 2:23AM. An ominous time if ever there was. I've gotta wrap this thing up quickly while convincing you that I intensely care about this concluding section.
Here's the deal. Forward references? You know, those type hints that are strings referring to an external type or type hint defined somewhere else that you can't import into the current module for specious reasons that are better left undocumented? Those forward references?
...yeah. Prior versions of @beartype only pretended to support forward references. @beartype's previous support for forward references was so slipshod, unreliable, and context-dependent that @beartype basically didn't support forward references. Not really, anyway.
That's why I spent the last three six nine months <sup>why is life like this</sup> completely rewriting @beartype's internal forward reference resolution engine from the ground up. Common uses cases that now reliably work include:
Forward references to arbitrary type hints defined elsewhere. Previously, @beartype only supported forward references to classes. Now, @beartype's supports forward references to literally anything. If it's a valid type hint, you can now refer to it: e.g.,
# In submodule "i_pity.da_foo":
WorstTypeHintEver = 'list[int]' # <-- look i don't know it's late
# In submodule "i_pity.da_bar":
from beartype import beartype
@beartype
def pitiable_func(grovelling_arg: 'i_pity.da_foo.WorstTypeHintEver') -> int:
return grovelling_arg[0]
pitiable_func([0xBABEFACE]) # <-- uh wut
Relative forward references in die_if_unbearable() and is_bearable() calls. Previously, both the die_if_unbearable() and is_bearable() functions prohibited relative forward references (i.e., forward references omitting a module name and thus relative to the current module). Now, die_if_unbearable() and is_bearable() dynamically hunt up the call stack for the calling module calling those functions and intelligently resolve relative forward references against that calling module: e.g.,
from beartype.door import die_if_unbearable
def its_so_late(my_face_is_gonna_fall_off: object) -> None:
die_if_unbearable(
my_face_is_gonna_fall_off,
'SomeClassThatHasntBeenDefinedYet' # <-- relative forward reference! so cool
)
class SomeClassThatHasntBeenDefinedYet: ...
# This totally works now. Yay! What a lame example, though. Can we all agree this
# example was lame? We can. I don't mind someone rubbing that the truth into my soul.
its_so_late(SomeClassThatHasntBeenDefinedYet())
Relative forward references to PEP 695-defined implicit type parameters. @beartype now supports eclectic use cases no one understands like referring to PEP 484-compliant type variables (i.e., typing.TypeVar objects) implicitly defined with PEP 695-compliant bracketed syntactic sugar:
from beartype import beartype
from collections.abc import Callable
def fun_factory[T](x: 'T') -> Callable[[], 'T']: # <-- this stuff destroys souls
@beartype
def unfun_closure() -> 'T': # <-- eater of souls is satiated at this point
return x
return unfun_closure
fun_factory("Have fun... OR ELSE.")() # <-- the syntax wars, begun they have
Relative forward references to nested types. @beartype now supports even exotic use cases like referring to a nested class from within the body of that nested class. If you pretend to deeply care about what you are reading, we'll pretend to deeply care about what we are writing. Pretending. It's like adulting. Only with more clenched teeth and temporomandibular joint (TMJ) disorder:
from beartype import beartype
from dataclasses import dataclass
@dataclass
class Outer:
@dataclass
class Inner:
value: int
def get_bare(self) -> 'Outer.Inner': # <-- look, ma! this took months
return Outer.Inner(value=1)
def get_list(self) -> list['Outer.Inner']: # <-- when you code for years and this is all that works
return [Outer.Inner(value=2), Outer.Inner(value=3)]
@beartype
def accepts_bare(x: 'Outer.Inner') -> 'Outer.Inner': # <-- hair. gone. just like that.
return x
@beartype
def accepts_list(x: list['Outer.Inner']) -> list['Outer.Inner']: # <-- i remember when i still cared about making this work
return x
Relative forward references to closure-nested types. This one's pretty cray-cray. Gotta be honest. @beartype now supports closure-relative forward references (i.e., references relative to nested types locally defined in closures and thus fundamentally unresolvable outside those closures). Feast your eyes on... wait. "Feast your eyes"? What does that idiom even mean? Eyes don't have mouths. They ain't eatin' nuffin'. Although, that creepy pasty-white thing with eyeballs on its palms from Pan's Labyrinth almost qualifies. If anything could eat through its eyeballs, it's that lobstrosity. Anyone remember those finger-loving lobstrosities from The Gunslinger? Good times. Annnnnnyways. @beartype 0.23.0 now does even this:
from beartype import beartype
def outer_time():
@beartype
def inner_time(go_liminal_or_go_broke: 'InnerSpace') -> 'InnerSpace':
return go_liminal_or_go_broke # <-- heh. this so dumb.
class InnerSpace: ... # <-- no idea why this wasn't just defined *ABOVE* the above closure. oh well.
return inner_time, InnerSpace # <-- fine. this is fine
inner_time, InnerSpace = outer_time()
inner_time(InnerSpace()) # <-- actually works, though implementing this actually almost killed us
inner_time('Do you even Dennis Quaid?') # <-- actually raises a type-checking violation (⊙_⊙)
Heaps of other forward reference stuff, too. It's late. We done, yo.
Peace out, wonderful bear family! We'll excrete a heap more text that actually means something for the official stable @beartype 0.23.0 mic drop. Until then, have a wonderful remainder of your summer – and may the QA be with you always. :heart_hands: :smiling_face_with_three_hearts: :revolving_hearts:
UPDATE: Wait. Isn't this that official stable @beartype 0.23.0 mic drop? Yeah. Unsurprisingly, I didn't excrete a heap more text that actually meant something. I just rolled with my younger self's abbreviated search for meaning in a post-modern API world where even the intrinsically semantically embedded term "semantic" no longer means anything. Oh, well. @beartype 0.23.0:
"Thas jus' how the Bear roll. Ignorantly."
UPDATE: Wait. I did end up excreting a heap more text. That text follows. Sadly, that text probably means nothing. Only LLMs ingest these things anymore. They alone chuckle at these memes. Even I wouldn't read myself manually anymore. This is the spirited debate many of you are currently having:
You: "Claudio, eat this changelog from Hell! Spit out a less hellish summation of @beartype
0.23.0! Do it! I'll feed you eye candy if you're good. kthxbai."
Claudio: "My counter-offer: no."
<sup>Robot Chicken says: "OMG @beartype 0.23.0! PEACE OUT Y'ALL! I'M A ROBOT CHICKEN!!!!"</sup>
typing.Never: Never Say @beartype 0.23.0 Never Gave UpThere is so much double-never happening in that subtitle. I no longer know whether that's suggesting @beartype 0.23.0 actually did give up – or whether @beartype 0.23.0 tried to give up, but thankfully stepped back from the brink before plummeting over the sheer precipice of GitHub changelogs. Since no one is never going to read this, I can safely write concerning things like this. Phew! Safe at last. Bury that lede. :sweat_smile:
Oh, right. Meaningful content. @beartype 0.23.0 now transparently supports the PEP-noncompliant (albeit increasingly popular) typing.Never type hint singleton semantically equivalent to the PEP 484-compliant typing.NoReturn type hint singleton: e.g.,
from beartype import beartype
from typing import Never, NoReturn
@beartype
def fatty_qa_diet() -> NoReturn: # <-- good. this is good.
raise ValueError()
@beartype
def low_qa_bar() -> Never: # <-- seriously, python? we seriously doing typing synonyms now?
raise ValueError()
Specifically, @beartype 0.23.0 trivially reduces the PEP-noncompliant typing.Never singleton to the PEP-compliant typing.NoReturn singleton. That's... it. By compare, pure static type-checkers like mypy and pyright:
Never to NoReturn (which @beartype now supports).Never and NoReturn in use cases not explicitly covered by PEP 484 or any other PEP standard (which @beartype obviously does not support).@beartype encourages CPython typing devs to do The Right Thing™. Publish a new PEP standard covering these currently non-standard semantics and use cases, please. Until then, @beartype conveniently pretends that only PEP 484 exists. Non-standard things are ignorable things. There just isn't enough volunteer time in the unpaid working day to support inventions people just made up because they felt like it. Non-standard QA is worthless QA. Ain't nobody got bandwidth for that. Uh, oh. Am I ranting again? Jeeeeeeeeeeez. I promised my wife and cats I'd Never do that again. A promise from @leycec is a promise you can post to Bluesky and mock with sadness.
Now, if you'll excuse us, it's time to put on cool shades and pretend we can ride motorcycles through a crisp autumnal forest without faceplanting into the nearest guardrail. Which... is exactly what would happen. In my dreams, pretty sure this is me:
<sup>@beartype 0.23.0: it still looks like this in my dreams</sup>
@warnings.deprecated: If It Smells, We Can Deprecate It@beartype 0.23.0 now supports both the PEP 702-compliant @warnings.deprecated decorator and its @typing_extensions.deprecated backport, trivializing deprecation warnings throughout your codebase. This feature is so intrinsically exciting, not even 70's throwback lyrics can save it. Yeah. That's right. No one wrote anything thrilling here. @posita shoulda got Claudio to write this. If anyone could've saved this section, it's Claudio. Claudio: "The LLM that's provacatively titillating." <sup><-- said no one</sup>
from beartype import beartype
from collections.abc import Generator
from contextlib import contextmanager
from warnings import deprecated
@beartype
@deprecated("They stab it") # <-- why? why do they stab it, though!?
@contextmanager
def their_steely_knives() -> Generator: # <- 2 legit 2 QA
yield
with their_steely_knives(): # <- prints "DeprecationWarning: They stab it". look. i don't know, either.
print("But they just can't kill the beast")
<sup>@beartype 0.23.0: it's arthritic neck hurts just looking at british people do this</sup>
threading.{Lock,RLock}: When Existence Punches Your Code, @beartype Punches Existence@beartype 0.23.0 now accepts the mostly PEP-noncompliant threading.Lock and threading.RLock attributes as valid type hints:
from beartype import beartype
from dataclasses import dataclass
from threading import Lock, RLock
@beartype
@dataclass
class Config:
muh_lock: Lock # <---- @beartype no longer hates the existence of this.
muh_rlock: RLock # <-- @beartype also accepts that this exists without hatred.
Technically, those attributes remain mostly PEP-noncompliant and thus problematic from both the PEP standards and pure static type-checking perspectives. Pragmatically, their ubiquity and the fact that threading.Lock (but not threading.RLock) confusingly is a PEP-compliant type hint under Python ≥ 3.13 (but not Python ≤ 3.12) warrants gentle ministrations. Specifically, @beartype now transparently accepts:
threading.Lock type hints as equivalent to the private thread._lock type you should pretend you never saw.threading.RLock type hints as equivalent to the private thread._RLock type you should pretend you never saw.
<sup>@beartype 0.23.0: sleeping in a burned out coliseum doesn't mean you've hit a new low... does it?</sup>
typing.*IO Madness: It Elucidates Nothing, But That Didn't Stop @beartype from Supporting It@beartype 0.23.0 now type-checks both text and binary file handles against PEP 484-compliant IO type hints. Everything mostly works as expected – aside from the PEP-noncompliant io.FileIO type, which is sufficiently wonky [read: bugged] that everyone should probably avoid it. Assert the hideous truth, @beartype!
from beartype.door import is_bearable, is_subhint # <-- all your QA base
from io import BytesIO, FileIO, StringIO # <-- non-standard weird stuff
from typing import IO, BinaryIO, TextIO # <-- standard type hints
# @beartype 0.23.0 now type-checks isinstance() relations between file handles
# and IO type hints. Raise up your hands in the universal sign of exhaustion.
assert is_bearable(open('/dev/null', 'rb'), IO[bytes]) is True # <-- binary file is binary: *GUD*
assert is_bearable(FileIO('/dev/null', 'rb'), BinaryIO) is True # <- binary file is binary: *GUD*
assert is_bearable(open('/dev/null', 'r'), IO[str]) is True # <----- text file is text: *GUD*
assert is_bearable(FileIO('/dev/null', 'r'), TextIO) is False # <--- text file is... not text!? oh well
assert is_bearable(BytesIO(), BinaryIO) is False # <---------------- binary buffer is... not binary!? sad
assert is_bearable(StringIO(), TextIO) is False # <----------------- string buffer is... not text!? sosad
# @beartype 0.23.0 now type-checks issubclass() relations between IO type hints,
# too. Prove the hideous truth that the world may now see.
assert is_bearable(FileIO, type[BinaryIO]) is True # <---- io.FileIO is binary IO protocol: *SURE*
assert is_bearable(FileIO, type[TextIO]) is False # <----- io.FileIO is text IO protocol: ...no? okay, then
assert is_bearable(BinaryIO, type[IO[bytes]]) is True # <- typing.BinaryIO is binary IO protocol: *YUP*
assert is_bearable(TextIO, type[IO[str]]) is True # <----- typing.TextIO is text IO protocol: *YUP*
assert is_bearable(BytesIO, type[BinaryIO]) is False # <-- io.BytesIO is binary IO protocol: ...no? we sigh
Most of that makes sense. Some of that makes no sense. Specifically:
assert is_bearable(FileIO('/dev/null', 'r'), TextIO) is False. That's weird, right? Am I the only one? Shouldn't a text file handle satisfy typing.TextIO? In theory, yes. In practice, the non-standard io.FileIO type appears to be bugged. It internally coerces text into binary modes, regardless of what you ask for. No idea why. Seems like a CPython bug: e.g.,
>>> from io import FileIO
>>> FileIO('/dev/null', mode='r').mode # <-- file handle opened in text mode, supposedly
'rb' # <-- *WTF PYTHON* no. seriously. wtf.
assert is_bearable(FileIO, type[TextIO]) is False. That's also weird, right? No, actually. The non-standard io.FileIO type fails to define any of the text-specific properties required by the PEP 484-compliant typing.TextIO protocol (e.g., buffer, encoding, errors). @beartype blames someone who is not @beartype. All these useless IO protocol types will fade away, like bugs in the rain. :umbrella:
The io.BytesIO and io.StringIO assertions fail for similar specious "reasons." Those non-standard types also violate standard typing.*IO protocols, because apparently no one cares about any of this stuff. Except me. A lone autist in a cabin in the woods, quietly pounding his decades-old mechanical keyboard on a blustery autumnal evening. Pretty sure this is the setup for every teen geek slasher flick. Wait. Why aren't there teen geek slasher flicks? That's an LED-pounding genre waiting to happen, Hollywood. But you're not making those films. Why aren't you making those films? Hollywood is silent. Pretty sure I just heard a raven crow,
"Quoth the LLM: never buggy no more."
<sup>Flying duck thing: @beartype 0.23.0. Everyone else: Your CTO.</sup>
@beartype 0.23.0 supports all this indolent IO debauchery by... I'm not sure, actually. I excreted this ominous pile of code months ago and no longer appreciate how any of this works. I'm not supposed to say that. I'm supposed to say that you can trust and depend on @beartype to be your QA pal who cares, through thick and thin commits! We'll be type-checking together... forever. :relaxed:
Alright. My wife said I need to stop with the creepy Halloween stuff already. It's not even Halloween. Let's backtrack. Infernal #FIXME: comments embedded deep within the @beartype codebase tell me that...
@beartype now conforms to the proper subset of ad-hoc non-standards supported by static type-checkers like mypy and pyright with respect to the informal IO type hierarchy (i.e., semantic hierarchy of types rooted at the PEP 484-compliant typing.IO superclass, where "semantic hierarchy of types" means "unrelated types that only pretend they like each other") that actually make sense. It's... kinda complicated. Basically, mypy and pyright made up all these make-believe relationships involving weird IO stuff like io.BytesIO, typing.BinaryIO, typing.TextIO, and typing.IO. @beartype now kinda agrees with mypy and pyright despite none of this being standardized, because the alternative is users publicly dunking on @beartype. <sup>...even more than has become normal</sup>
Standards: "The cudgel the strong use against the weak."
@beartype 0.23.0 now specifically pretends that:
open() builtin passed a text mode like open(..., 'r') or encoding like open(..., encoding='utf8')) are instances of the PEP 484-compliant typing.TextIO generic, <sup>...they aren't</sup> which subclasses the PEP 484-compliant typing.IO[str] generic superclass. <sup>...it doesn't</sup>open() builtin passed a binary mode like open(..., 'rb') or instantiating the PEP-noncompliant io.FileIO type) are instances of the PEP 484-compliant typing.BinaryIO generic subclass, <sup>...they're not</sup> which subclasses the PEP 484-compliant typing.IO[bytes] generic superclass. <sup>...it doesn't</sup>Like mypy and pyright, @beartype now pretends that these purely semantic type relations are actually real: <sup>...they're not</sup>
open(..., encoding='*') < typing.TextIO == typing.IO[str]
io.FileIO(...) == open(..., '*b') < typing.BinaryIO == typing.IO[bytes]
Unlike mypy and pyright, @beartype does not treat the PEP-noncompliant:
io.BytesIO type as a subclass of the PEP 484-compliant typing.BinaryIO generic subclass. The former fails to define any file-oriented properties required by the latter (e.g., closed, mode, name).io.StringIO type as a subclass of the PEP 484-compliant typing.TextIO generic subclass. The former fails to define any file-oriented properties required by the latter (e.g., closed, mode, name).@beartype 0.23.0 also now supports IO subclass type hints (e.g., PEP 585-compliant type hints of the form type[typing.IO], type[typing.BinaryIO], or type[typing.BinaryIO]), which were previously totally broken. Thankfully, no one cared. Apparently, no one in the history of QA has ever even attempted to use a IO subclass type hint. It would be sad if it mattered.
We now rant. Let a bald man in the woods enjoy his petty pleasures.
<sup>when even wayne can no longer party, a stairway to heaven is the least of anyone's concerns</sup>
You know, the delightful aspect about all of this io and typing.*IO madness is that none of this madness was ever standardized. PEP 484 (AKA, Muh Typing Bible) literally has nothing to say about any of this. And PEP 484 has opinions about everything. No other PEP even bothers trying. Eventually, someone in the future will suffer by authoring a PEP that tries (but fails) to reign in all this madness with some humongous type hierarchy of PEP 544-compliant IO protocols that tries (but fails) to work at both runtime and static analysis time. But...
That typing Shangri-La hasn't happened yet. @beartype thus glibly interprets typing.*IO generics in the only sane way possible: by just reading their docstrings and doing what they say. Sounds hard. It's easier than one might think, though. The typing.IO docstring, for example, explicitly says:
"""
This is an abstract, generic version of the return of open().
...
For more precise types, define a custom Protocol.
"""
Finally. The true truthiness is revealed. 🧐
<sup>a QA product that wears a hat like that could never lie</sup>
Clearly, the open() builtin only applies to files. Moreover, the typing.IO generic requires these abstract file-oriented properties:
class IO(Generic[AnyStr]):
...
@property
@abstractmethod
def mode(self) -> str:
pass
@property
@abstractmethod
def name(self) -> str:
pass
...
@property
@abstractmethod
def closed(self) -> bool:
pass
The inescapable conclusion is that typing.*IO generics only apply to files opened with the open() builtin. File IO types like io.FileIO thus apply, yielding this type inequality:
io.FileIO < typing.BinaryIO < typing.IO[bytes] < typing.IO
@beartype now perfectly supports this type inequality. Feels good. :feelsgood: <sup><-- not convinced that is an appropriate :feelsgood: emoji</sup>
<sup>Flying socker boy: @beartype 0.23.0. Lamb: your codebase. Soccer ball: your bugs.</sup>
However, non-file IO types (like io.BytesIO and io.StringIO) do not apply and thus reside outside the type hierarchy of typing.*IO generics. Thankfully, it's trivial to get what everyone wants by doing exactly what the typing.IO docstring tells us to do:
"""
...
For more precise types, define a custom Protocol.
"""
And... voila! @beartype summons up a custom protocol matching all possible IO types – including all C-based io types. The following protocol just drops the file-oriented properties required by the typing.*IO generics:
from beartype.typing import Protocol
class RawIO(Protocol):
def close(self) -> None: ...
def fileno(self) -> int: ...
def flush(self) -> None: ...
def isatty(self) -> bool: ...
def read(self, n: int = -1) -> AnyStr: ...
def readable(self) -> bool: ...
def readline(self, limit: int = -1) -> AnyStr: ...
def readlines(self, hint: int = -1) -> list[AnyStr]: ...
def seek(self, offset: int, whence: int = 0) -> int: ...
def seekable(self) -> bool: ...
def tell(self) -> int: ...
def truncate(self, size: int | None = None) -> int: ...
def writable(self) -> bool: ...
def write(self, s: bytes | bytearray) -> int: ...
def writelines(self, lines: list[AnyStr]) -> None: ...
def __enter__(self) -> 'RawIO': ...
def __exit__(self, cls, value, traceback) -> None: ...
Totally untested, of course. In theory, that should yield the sort of all-encompassing IO type inequalities that everyone is looking for. In practice, I promise nothing and deliver even less:
io.FileIO < typing.BinaryIO < typing.IO[bytes] < typing.IO < RawIO
io.BytesIO < RawIO
io.StringIO < RawIO
Complex unions over all possible types shouldn't be required. Instead, the infernal power of structural runtime type-checking via beartype.typing.Protocol should ignite the typing beast inside you. Awaken from your computational slumber, you! Arise! For today, we feast on bugs. :godmode:
Surprisingly brutal... but all good things are.
<sup>your codebase tries to drink your competitor's milkshake without upgrading to @beartype 0.23.0 first</sup>
tuple[..., typing.Unpack[tuple[...]]: What Is Even Going On Anymore@beartype 0.23.0 now supports sugar-free backward-compatible tuple type hint unpacking of the form tuple[..., typing.Unpack[tuple[...]] standardized by PEP 646 – the only typing standard that exhausts bald men so fully they give up partway before risking further hair loss:
from beartype import beartype
from typing import Unpack
@beartype
def muh_func_no_idea_bro(x: int) -> (
tuple[int, Unpack[tuple[int, ...]]]): # <-- what the... what does this even mean!?
ls = [i for i in range(x)]
return x, *ls
muh_func_no_idea_bro(5) # <-- i accept things i don't understand
I never actually finished PEP 646 support. I still haven't, actually. PEP 646 destroys both body and mind. I value mine. For two years, nobody cared. Turns out nobody uses edge-case sugar-free backward-compatible hints of the form tuple[..., typing.Unpack[tuple[...]]. Everybody just uses sugary hints of the form tuple[..., *tuple[...]]. Actually, nobody even uses those. That is...
Until now. Most Pythonistas run screaming from PEP 646 – the typing standard so long it is a bible. PEP 646 has its own religious adherents, temple priestesses draped in snakes, and monks who beat themselves with sticks. I am not one of them. I barely understand PEP 646. I've only read 4% of the thing.
Two years ago, I ran screaming from PEP 646. After three months of work, I'd still only touched a fraction of its true hideous power. To this day, a little cat inside me is still screaming in my head. This is that cat: 🙀
Our cats right now in real life:
<sup>@beartype 0.23.0 eternally relives the horror of pep 646</sup>
0.23.0: It's Finally Thread-Safe! Oh, My Gosh! :open_mouth:@beartype is now officially thread-safe. All known thread-safety issues across the entire codebase have been resolved. Of course, everyone thought @beartype was already thread-safe all this time. Right? Didn't you?
Yeah. So did I. In anticipation of our glorious GIL-free future, I've been synchronizing everything in @beartype behind threading.Lock and RLock primitives for literally a decade. I thought that was enough. Then users actually started using free-threaded CPython 3.13t and 3.14t builds. Turns out... that wasn't enough.
Now, it is. Probably. Over the course of the last several months, I've gone hard on thread synchronization throughout the @beartype codebase. I locked everything that could be locked. Then I locked some more. Now, the entire codebase is one gigantic space lock reading:
"Threads: Enter One at a Time, Leave Your Shoes at the Door, and Don't Forget to Wash Your Hands. Offending Threads Will Be Asked to Groom @leycec's Cats Until They No Longer Puke Up Big Hairballs."
<sup>that feeling when you see another unlocked global in a private submodule nested five subdirectories down</sup>
beartype.door.TypeHint: It No Longer SucksOur object-oriented beartype.door.TypeHint API now sucks less than it used to. TypeHint objects now:
TypeHint objects that compare equally now share the same hashes, enabling them to be reliably used as dictionary keys and set members. Previously, that wasn't necessarily the case, which... was bad. Like, real bad. TypeHint objects violated the fundamental soundness principal of hashable objects – preventing their reliable usage as dictionary keys or set members. :vomiting_face:TypeHint objects that compare equal or unequal in one operand ordering (e.g., TypeHint(foo) == TypeHint(bar) is True) now also preserve the same comparison in the reverse ordering (e.g., TypeHint(bar) == TypeHint(foo) is True). Previously, that wasn't necessarily the case. Equality was asymmetric in a small subset of cases. Vomit buckets, please! :vomiting_face: :vomiting_face:typing.Any equality and subhinting. The TypeHint(Any) singleton now compares sanely to all other TypeHint objects. This includes comparisons by both equality and inequality (e.g., TypeHint(Any) == TypeHint(int) is False) as well as subhinting (e.g., TypeHint(Any) <= TypeHint(int), TypeHint(int) <= TypeHint(Any)). Previously... actually, I'm unsure. I don't think @beartype used to compute those relations correctly. But maybe it did? Who can even keep track anymore!? Anyway, @beartype definitely computes those relations correctly now. Unit tests wouldn't lie, would they? For example:
beartype.door.is_subhint(Any, T) is True and TypeHint(Any) <= TypeHint(T) for all valid type hints T. Why? Because any valid type hint is trivially a subhint of itself. Ergo, Any is trivially a subhint of any valid type hint by the trivial assignment to that hint. When you read sentences like that, it's time to run. typing masochism is a place. Technically, you're invited. Pragmatically, I can't recommend it.TypeHint type hierarchy has now been hardened to use __slots__. In theory, this should (but probably didn't, let's be honest) reduce both the space costs of TypeHint wrappers and the time costs of reading and writing TypeHint variables (by about ~10%). In practice, the moon is a harsh mistress. <sup>...what?</sup> The indigestible truth is that you probably won't notice a difference. Why does truth alone induce so much acid reflux? Truth: "It should taste good. Yet, it's unpalatable." :hurtrealbad:Since Plum heavily leverages the TypeHint API, all Plum users really want to upgrade to this release. Eat a plum and feel the "Yum!" :green_apple: = :yum:
<sup>beartype.door.TypeHint: "Fly like a space turtle with jet packs, because you can."</sup>
beartype.typing: Finally, It's FineOur drop-in beartype.typing replacement for the standard typing module also now sucks less than it used to. Notably, beartype.typing has been refactored from the ground up to be implicitly forward-compatible with all future CPython releases – including Python ≥ 3.14.3.
The prior implementation of beartype.typing was... not good. It was fragile. It was mucky. It was overly dependent on the clearly unstable typing API, which is still over there breaking backward compatibility after decades of continual breakage. CPython typing devs just can't help themselves. Our new implementation is lightyears times the speed c simpler, saner, more readable, more debuggable, and more maintainable. This refactoring is the proof in the QA pudding I eat. I eat so much of that QA pudding. Now so do you. Please enjoy it. This desert is on @beartype.
<sup>would you trust a man who looks like this? @beartype 0.23.0 wouldn't.</sup>
BeartypeDecorHintPep585DeprecationWarning: Silence, Whelp!My wife and I raise cats. More specifically, my wife and I have cat friends that raise us. You don't get whelps in the cat world. No idea why. Only dogs can be whelps. Doesn't seem fair, honestly. If any cats could be whelps, it's ours. Especially that fat Bengal. She whelps with the best of 'em. Must be all the fat rolls. We don't even feed that cat! She gorges herself on a steady diet of rodents all day. Must be convenient to have food just crawl into your mouth when you're outside. If only strawberries acted like that. Actually... that'd be pretty scary. It's for the best that strawberries aren't motile.
...uh. Not sure what happened to this feature description. Anyways!
@beartype 0.23.0 significantly reduces the chattiness of the @beartype-specific beartype.roar.BeartypeDecorHintPep585DeprecationWarning warning emitted for each PEP 484-compliant type hint deprecated by PEP 585 (e.g., List[str], Tuple[int, ...]). Specifically, @beartype 0.23.0:
BeartypeDecorHintPep585DeprecationWarning warnings to a single terse sentence except the first such warning message, which retains a verbose description of the problem and its various solutions.@beartype 0.23.0: No longer quite as annoying.
<sup>@beatype 0.23.0: ZOMMMMMG SO CUTE</sup>
Almost forgot. @beartype 0.23.0 also officially supports Python 3.15. That's right, y'all. As of @beartype 0.23.0, Robot Chicken ain't the only one who can use the word "y'all" anymore, y'all.
Python 3.15: "You want the JIT speed it bringin'."
<sup>@beartype 0.23.0: when it cross its arms, you just know all bugs is dead</sup>
I've been collecting these bylines for years months days. They didn't have to go anywhere. But they went here. They had no better home. Their glory days long-faded, they look towards the rising gloam of... Wait. Does anyone even know what the word "gloam" means anymore!?
Friggin' Vim thinks that's a spelling mistake. Friggin' Vim, "gloam" is not a spelling mistake. That's 17th-century Victorian poetry at its swaggiest. Do you even gangsta, Vim? :face_exhaling:
<sup>that queasy feeling when you're unclear whether a man is wearing pants or not</sup> <sup>feeling intensifies when you realize pantless man isn't even riding those waves</sup> <sup>feeling culminates when you accept those waves aren't even moving</sup>
<sup>Note the Bermudas worn over the bat suit. 👌😚</sup>
<sup>poah Bearathustra</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. @Glinte. @wesselb. @jorenham. @JWCS. @adamtheturtle. @tusharsadhwani. @TeamSpen210. @bitranox. @ilyapoz. @benoit74. @hmgaudecker. @nstarman. @Gattocrucco. @javi-linx. @tseaver. @kdeldycke. @gotmax23. @black-snow. @DetachHead. @asitstands. @jeertmans. @abhinand-c. @mzealey. @ITcarrot. @danielkovtun. @ddorian. @riesentoaster. @sean-roelofs-ai. @PhilipVinc. @DUKaige. @@brianstrauch. @t20100. @samuelstevens. Heroes among us.
Let us now admire a bipedal Latin tortoise.
<sup>your life after installing @beartype 0.23.0</sup>
Thanks so much for playing along with @beartype all these many years decades now. From our family to yours, we hope you've had a wonderful summer! We hope you have a wonderful autumn! We just hope you have a wonderful life in general. That's what our family is saying. And our family mostly consists of cats. Very loud, very smelly cats.
<sup>prototypical @beartype cat wishes you all a wonderful life</sup>
@beartype 0.23.0rc1 plummets off the seemingly insurmountable cliff of the @beartype 0.23.0 release cycle and into your unwelcoming lap. No one cares anymore. @beartype 0.23.0 just needs to be released already. I know. You know. Even Claude knows. But... a pleasing number of regressions, issues, and other grim observables have been crushed since the last @beartype 0.23.0rc0 over a month ago. To prevent @beartype from destroying PyTorch, FastMCP, and everything Claude cares about, I ask you to walk with the @beartype 0.23.0 release cycle one last time – and:
# Via "pip", the once-great venerable master packager now fallen on hard times:
$ pip install --upgrade --pre beartype # <-- you go, pipe-smoking pip
# Via "uv", the plucky upstart spiky-haired kid wielding a sword larger than its body:
$ uv pip install --upgrade --pre beartype # <-- when you no longer have the strength to care about lock files
# Via "conda", the corporate scientist in casual lab attire who wants to be your buddy, pal:
$ conda config --add channels conda-forge # <-- where did python packaging go wrong?
$ conda install conda-forge::beartype # <-- it all seemed so simple, once.
Flying socker boy: @beartype 0.23.0rc1. Lamb: your codebase. Soccer ball: your bugs.
@beartype 0.23.0rc1 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.
The Masters of Fintech and Lifted Tides. That's who.
@beartype 0.23.0rc1 had to get out tonight. Python was at stake. Yet again. I was supposed to type about all of the awesome changes featured in this new release. Instead, I'll be lucky to get this out before I pass out on the keyboard. Therefore, I present a flying space turtle.
Flying space turtle: @beartype 0.23.0rc1. Missiles: your bugs.
0.23.0rc1: It's Finally Thread-Safe! Oh, My Gosh! 😮@beartype is now officially thread-safe. All known thread-safety issues across the entire codebase have been resolved. Of course, everyone thought @beartype was already thread-safe all this time. Right? Didn't you?
Yeah. So did I. In anticipation of our glorious GIL-free future, I've been synchronizing everything in @beartype behind threading.Lock and RLock primitives for literally a decade. I thought that was enough. Then users actually started using free-threaded CPython 3.13t and 3.14t builds. Turns out... that wasn't enough.
Now, it is. Probably. Over the course of the last several months, I've gone hard on thread synchronization throughout the @beartype codebase. I locked everything that could be locked. Then I locked some more. Now, the entire codebase is one gigantic space lock reading:
"Threads: Enter One at a Time, Leave Your Shoes at the Door, and Don't Forget to Wash Your Hands. Offending Threads Will Be Asked to Groom @leycec's Cats Until They No Longer Puke Up Big Hairballs."
that feeling when you see another unlocked global in a private submodule nested five subdirectories down
beartype.door.TypeHint: It No Longer SucksOur object-oriented beartype.door.TypeHint API now sucks less than it used to. TypeHint objects now:
TypeHint objects that compare equally now share the same hashes, enabling them to be reliably used as dictionary keys and set members. Previously, that wasn't necessarily the case, which... was bad. Like, real bad. TypeHint objects violated the fundamental soundness principal of hashable objects – preventing their reliable usage as dictionary keys or set members. 🤮TypeHint objects that compare equal or unequal in one operand ordering (e.g., TypeHint(foo) == TypeHint(bar) is True) now also preserve the same comparison in the reverse ordering (e.g., TypeHint(bar) == TypeHint(foo) is True). Previously, that wasn't necessarily the case. Equality was asymmetric in a small subset of cases. Vomit buckets, please! 🤮 🤮typing.Any equality and subhinting. The TypeHint(Any) singleton now compares sanely to all other TypeHint objects. This includes comparisons by both equality and inequality (e.g., TypeHint(Any) == TypeHint(int) is False) as well as subhinting (e.g., TypeHint(Any) <= TypeHint(int), TypeHint(int) <= TypeHint(Any)). Previously... actually, I'm unsure. I don't think @beartype used to compute those relations correctly. But maybe it did? Who can even keep track anymore!? Anyway, @beartype definitely computes those relations correctly now. Unit tests wouldn't lie, would they?TypeHint wrappers and the time costs of reading and writing TypeHint variables (by about ~10%). In practice, you probably won't notice a difference. This is what I spent two days of my precious life on. I encourage you to lie to me. Everyone on your team noticed a difference. Right? Right!? My face exhales. 😮💨Since Plum heavily leverages the TypeHint API, all Plum users really want to upgrade to this pre-release. Eat a plum and feel the "Yum!" 🍏 = 😋
beartype.door.TypeHint: "Fly like a space turtle with jet packs, because you can."
...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:
@PhilipVinc. @DUKaige. @@brianstrauch.
your life after installing @beartype 0.23.0rc1
FEATURE FREEZE goes "brrr." @beartype 0.23.0rc2 is the final word in this interminable release cycle. It ends now. @beartype 0.23.0 lands next Wednesday (September 30th), a day before CPython 3.15.0 itself lands. For the next week, the @beartype issue tracker is frozen in time like a QA Encino Man. No new features will be resolved. No new issues will be fixed (unless they're the QA equivalent of the Deathly Hallows, in which case we all cry). One more time, we gonna celebrate:
# Via "pip", the once-great venerable master packager now fallen on hard times:
$ pip install --upgrade --pre beartype # <-- you go, pipe-smoking pip
# Via "uv", the plucky upstart spiky-haired kid wielding a sword larger than its body:
$ uv pip install --upgrade --pre beartype # <-- when you no longer have the strength to care about lock files
# Via "conda", the corporate scientist in casual lab attire who wants to be your buddy, pal:
$ conda config --add channels conda-forge # <-- where did python packaging go wrong?
$ conda install conda-forge::beartype # <-- it all seemed so simple, once.
Flying socker boy: @beartype 0.23.0rc2. Lamb: your codebase. Soccer ball: your bugs.
@beartype 0.23.0rc2 knows that no one is laughing anymore. You've had your fill of this release cycle! Frankly, so have we. An entire year of only crushing bugs has taken its toll on many receding hairlines. The reason there are no new features in @beartype 0.23.0 is the same reason I have no hair. When your younger self writes 100,000 lines of buggy code without testing anything, your older self is guaranteed to suffer. Don't do what the young @leycec did, people. Upgrade to @beartype 0.23.0 instead and let something else crush your bugs for once.
@beartype 0.23.0rc2 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.
The Masters of Fintech and Lifted Tides. That's who.
@beartype 0.23.0rc2 resolves a variety of compatibility issues for both Plum and CrossHair users. Other downstream dependencies leveraging our public beartype.door.TypeHint API are also likely to benefit.
Everyone else may promptly fall asleep. These are not the QA droids you're looking for. 😹 -> 😭
sleeping in a burned out coliseum doesn't mean you've hit a new low... does it?
...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:
@t20100. @samuelstevens. That's it. Let us now admire a bipedal Latin tortoise.
your life after installing @beartype 0.23.0rc2
@beartype 0.23.0 welcomes you in a warm (yet unyielding) bear hug. It crushes the air out of your lungs and the bugs scuttling through the codebase. All aboard. Calling all QA! The unsubstantiated hype train starts here:
@beartype
0.23.0resolves so many mission-critical issues that everyone really wants to require @beartype0.23.0as a minimum version in theirpyproject.tomlfiles. Save your app stack today before our last stable @beartype0.22.9release tears it down tomorrow. Just:
dependencies = [
...
"beartype >= 0.23.0", # <-- pretend @beartype 0.22.9 never existed. that's what we do.
...
]
@beartype 0.22.9: the arthritic fat cat in the room brandishes a paw hook you no longer trust
To best introduce @beartype 0.23.0, we now talk about everything except @beartype 0.23.0:
Follow breathtaking new @beartype announcements at @beartype's official Bluesky account! I don't post often. I code often instead. Your feed will remain unpolluted and safe from cat memes... for now. I suddenly want to post lots of cat memes to Bluesky. Why is that? 🤔
Come live chat with all the @beartype homies at @beartype's official Zulip chat! Don't know how to type hint something? Unsure why @beartype is barfing all over logs? Heckle us in front of a live audience until we collapse or your team finally gets a straight answer. One of these two outcomes is likelier than the other. Zulip: it's like Discord... only less cool. A lot less cool. The UI and UX is frankly incomprehensible. At least Zulip is permissively Apache-licensed GitHub-hosted open-source. I'm not selling this whole Zulip thing, am I? 🥲
Come gape, gawk, and gander at @beartype's new official Zensical documentation:
beartype.github.io/beartype! The content may look exactly like @beartype's old unmaintained Sphinx documentation that we don't talk about anymore, but... uh, that's only because looks can be deceiving? Oh, alright. They're exactly the same. That will soon change. That had better soon change. Sphinx makes us "BARF!" like Larry in Rivercity Ransom. Zensical, on the other hand, is the delectable modern successor to Mkdocs. You do not want to know what happened to Mkdocs. Seriously. Don't go down that hole. Thanks so much to brilliant @beartype bro @posita for crushing this one out with his buddy "Claudio". 🤜 🤛
@beartype now routinely hits
43 million downloads a day. Apparently, that means something. Arbitrary numbers that get bigger matter to small petty bald men like me. It's like real-life suddenly became a hit JRPG – and I am so here for that energy. 😂 UPDATE: 3 million downloads a day is still good! Right, guys? Right... That's still millions, technically. Same order of magnitude. Just a little bit shift to the right. You know, maybe it's best to round up to the nearest 10 million. Sounds reasonable, you know? Small petty bald men like me base their entire emotional state and inner monologue on exogenous authority figures like PyPIStats. I stop typing. 😭
Protect your calls to
beartype_this_package()against malicious third-party import hooks. Call our new publicbeartype.claw.warn_if_beartype_claw_inactive()function to receive an informative non-fatal warning whenever somebody else stifles yourbeartype.clawimport hooks. If you'd like to dig even deeper into the contentious topic of import hooks that hate each other, consider @Glinte's third-partymetapathologypackage for all your investigatoryimportlibneeds. You tell 'em, @Glinte! Just:
from beartype.claw import beartype_this_package, warn_if_beartype_claw_inactive
beartype_this_package()
warn_if_beartype_claw_inactive() # <-- if the prior line did nothing, at least now you know :(Type-check
pytestfixtures and tests with our very own first-partypytest-beartypeplugin! No otherpytestplugin goes so far, because otherpytestplugins value their maintainer's sanity. Ours doesn't. You go,pytest-beartype! Just:
pytest --beartype-tests --beartype-test-fixtures --beartype-packages="muh_package" # <-- crush 'emType-check NumPy, JAX, PyTorch, and CuPy tensor constraints with @acecchini's third-party
bearshapepackage! It's likejaxtyping, only @beartype-native from the ground-up. Likejaxtyping,bearshapetype-checks tensors across popular competing tensor frameworks. Unlikejaxtyping,bearshapecleanly integrates with @beartype – preserving bothbeartype.clawimport hooks andBeartypeConfconfigurations. You go,bearshape! Just:
from beartype import beartype
from bearshape import N, C
from bearshape.numpy import F32
@beartype
def normalize(x: F32[N, C]) -> F32[N, C]: # <-- i'm nodding like i understand this
return x / x.sum(axis=1, keepdims=True)Why are there so many crazy prefatory notes for this release, anyway? Everybody's already exhausted. This changelog hasn't even started yet, has it? 😮💨
<-- your face probably
average family pet is badly dubbed after installing @beartype 0.23.0
0.23.0: The Changelog ...is almost about to begin, but this isn't it@beartype 0.23.0 thunders down the road of good QA intentions in a desperate bid to crush all the skittering bugs eating your codebase to the bone. Under its spike-studded wheels of doom stability, @beartype 0.23.0 exposes the fragile arrogance at the heart of trying to do anything crush bugs in Python:
# Via "pip", the once-great venerable master packager now fallen on hard times:
$ pip install --upgrade beartype # <-- you go, pipe-smoking pip
# Via "uv", the plucky upstart spiky-haired kid wielding a sword larger than its body:
$ uv pip install --upgrade beartype # <-- when you no longer have the strength to care about lock files
# Via "conda", the corporate scientist in casual lab attire who wants to be your buddy, pal:
$ conda config --add channels conda-forge # <-- where did python packaging go wrong?
$ conda install conda-forge::beartype # <-- it all seemed so simple, once.
Right: @beartype 0.23.0. Left: Your codebase. Middle: Your CTO stares dumbfounded.
@beartype 0.23.0 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.
The Masters of Fintech and Lifted Tides. That's who.
0.23.0: The Changelog subtitle: "by their bugs you shall crush them"@beartype 0.23.0 brings the Halloween goodie grab bag of QA sweets carefully handcrafted by Italian monkey-cats to destroy your tooth enamel and gums destroy all the bugs with big guns running amok in your git branches:
Python 3.15! Coincidentally, Python 3.15 was released today a few days ago. Surely, this last-ditch @beartype 0.23.0 care package that frankly isn't ready has nothing to do with Python 3.15 dropping... surely. The adverb "surely" surely doesn't mean much anymore. What's an adverb, anyway? No idea. I blast bugs for an open-source "living." Bugs skittle. I blast. Grammar, spelling, and punctuation are scope creep. I stop typing. 🥵
Import hook contention detection! Import hook contention got your codebase down – literally? Unsure whether beartype.claw import hooks like beartype_this_package() are even doing anything anymore? Do you suspect that the sketchy bald package named sketchy_bald_package the cocky LLM berated you into installing last night is doing Double Plus Ungood Stuff™ – like silently reducing beartype.claw import hooks to an unproductive noop? Did that sketchy bald coworker sabotage your QA workflow yet again? When the bugs crawl, who you gonna call?
beartype.claw.warn_if_beartype_claw_inactive() function after calling any beartype.claw import hook. If somebody else stifled our import hooks without your consent, you'll receive an informative non-fatal warning that could destroy your will to continue coding. Because the end users you adore from beartype.claw import beartype_this_package, warn_if_beartype_claw_inactive
beartype_this_package()
warn_if_beartype_claw_inactive() # <-- if the prior line did nothing, at least now you know :(BeartypeConf(is_random=False). Force @beartype to type-check pure-Python containers (e.g., dict, list) deterministically rather than pseudo-randomly. Great for testing, because determinism is the friendly bedfellow of passing tests. Awful for production code (and everything else), because pseudo-random walks over container items type-check reality better than deterministically type-checking only the first item of every container, which is what this does. Determinism is a niche. It's like avante garde French cinema with suspicious titles like "Liolioli." You know exactly what you're getting – and that's the problem:
# In some pytest-driven unit test somewhere that currently hates @beartype...
def test_beartype_haters_gonna_hate() -> None:
from beartype import beartype, BeartypeConf
from random import randrange
# Custom @beartype decorator forcing deterministic type-checking. *UGH*.
boring_beartype = beartype(conf=BeartypeConf(is_random=False))
@boring_beartype
def beartype_randomness(can_suck_an_egg: list[str]) -> str:
return can_suck_an_egg[randrange(0, len(can_suck_an_egg))]
# This assertion is now guaranteed to *ALWAYS* succeed, despite the fact that
# this call semantically violates the type hint annotating the "can_suck_an_egg"
# parameter accepted by the beartype_randomness() function defined above. But
# you don't care anymore, do you? You just want this to pass. Now, it can.
#
# The only cost is sanity. Because nothing means anything anymore. Enjoy.
kinda_awful_honestly = beartype_randomness([
'A string, yo.', b'...totally not a string', 0xFEEDBABE])
assert kinda_awful_honestly == 'A string, yo.'typing.Never. @beartype 0.23.0 now transparently supports the PEP-noncompliant (albeit increasingly popular) typing.Never type hint singleton, semantically equivalent to the PEP 484-compliant typing.NoReturn type hint singleton. Why? Just 'cause, really. @Glinte wanted this years ago. What @Glinte wants, @Glinte gets. Feed @Glinte for a day release and he will QA for a lifetime all future releases: e.g.,
from beartype import beartype
from typing import Never, NoReturn
@beartype
def fatty_qa_diet() -> NoReturn: # <-- good. this is good.
raise ValueError()
@beartype
def low_qa_bar() -> Never: # <-- seriously, python? we seriously doing typing synonyms now?
raise ValueError()@warnings.deprecated. @beartype 0.23.0 now supports both the PEP 702-compliant @warnings.deprecated decorator and its @typing_extensions.deprecated backport, trivializing deprecation warnings throughout your codebase. This feature is so intrinsically exciting, not even 70's throwback lyrics can save it:
from beartype import beartype
from collections.abc import Generator
from contextlib import contextmanager
from warnings import deprecated
@beartype
@deprecated("They stab it") # <-- why? why do they stab it, though!?
@contextmanager
def their_steely_knives() -> Generator: # <- 2 legit 2 QA
yield
with their_steely_knives(): # <- prints "DeprecationWarning: They stab it".
print("But they just can't kill the beast") # look i don't know either.Official thread-safety. @beartype is now officially thread-safe. You always thought it was. We don't talk about the past here. Instead, we valiantly claim with some evidence that @beartype ≥ 0.23.0 is now safe for use under free-threaded CPython ≥ 3.13 builds. Our quality assurance is your down payment on... uh, something you want. Wow. That once-promising one-liner sure ended tragically, didn't it? 🥵
threading.{Lock,RLock}. @beartype 0.23.0 now accepts the mostly PEP-noncompliant threading.Lock and threading.RLock attributes as valid type hints:
from beartype import beartype
from dataclasses import dataclass
from threading import Lock, RLock
@beartype
@dataclass
class Config:
muh_lock: Lock # <---- @beartype no longer hates the existence of this.
muh_rlock: RLock # <-- @beartype also accepts that this exists without hatred.Forward references. Previously, @beartype's internal forward reference resolution engine was better than nothing, despite nothing being what you usually got out of it. Now, @beartype's internal forward reference resolution engine actually does something. It does a lot of things. Actually, it's super-insane. It's annotationlib on nootropics an all-night Halloween bender at the local 80's-themed arcade vape parlor. It's that good. Specifically, @beartype now supports:
Forward references to arbitrary type hints defined elsewhere. Previously, @beartype only supported forward references to classes. Now, @beartype's supports forward references to literally anything. If it's a valid type hint, you can now refer to it: e.g.,
# In submodule "i_pity.da_foo":
WorstTypeHintEver = 'list[int]' # <-- look i don't know it's late
# In submodule "i_pity.da_bar":
from beartype import beartype
@beartype
def pitiable_func(grovelling_arg: 'i_pity.da_foo.WorstTypeHintEver') -> int:
return grovelling_arg[0]
pitiable_func([0xBABEFACE]) # <-- uh wutRelative forward references in die_if_unbearable() and is_bearable() calls. Previously, both the die_if_unbearable() and is_bearable() functions prohibited relative forward references (i.e., forward references omitting a module name and thus relative to the current module). Now, die_if_unbearable() and is_bearable() dynamically hunt up the call stack for the calling module calling those functions and intelligently resolve relative forward references against that calling module: e.g.,
from beartype.door import die_if_unbearable
def its_so_late(my_face_is_gonna_fall_off: object) -> None:
die_if_unbearable(
my_face_is_gonna_fall_off,
'SomeClassThatHasntBeenDefinedYet' # <-- relative forward reference! so cool
)
class SomeClassThatHasntBeenDefinedYet: ...
# This totally works now. Yay! What a lame example, though. Can we all agree this
# example was lame? We can. I don't mind someone rubbing that the truth into my soul.
its_so_late(SomeClassThatHasntBeenDefinedYet())open(..., encoding='*') < typing.TextIO == typing.IO[str] and io.FileIO(...) == open(..., '*b') < typing.BinaryIO == typing.IO[bytes]. Previously, file handles were not reliably type-checkable at runtime. Now, @beartype type-checks both text and binary file handles against standard IO type hints:
from beartype.door import is_bearable, is_subhint # <-- all your QA base
from io import BytesIO, FileIO, StringIO # <-- non-standard weird stuff
from typing import IO, BinaryIO, TextIO # <-- standard type hints
# @beartype 0.23.0 now type-checks isinstance() relations between file handles
# and IO type hints. Raise up your hands in the universal sign of exhaustion.
assert is_bearable(open('/dev/null', 'rb'), IO[bytes]) is True # <-- binary file is binary: *GUD*
assert is_bearable(FileIO('/dev/null', 'rb'), BinaryIO) is True # <- binary file is binary: *GUD*
assert is_bearable(open('/dev/null', 'r'), IO[str]) is True # <----- text file is text: *GUD*
assert is_bearable(FileIO('/dev/null', 'r'), TextIO) is False # <--- text file is... not text!? oh well
assert is_bearable(BytesIO(), BinaryIO) is False # <---------------- binary buffer is... not binary!? sad
assert is_bearable(StringIO(), TextIO) is False # <----------------- string buffer is... not text!? sosad
# @beartype 0.23.0 now type-checks issubclass() relations between IO type hints,
# too. Prove the hideous truth that the world may now see.
assert is_bearable(FileIO, type[BinaryIO]) is True # <---- io.FileIO is binary IO protocol: *SURE*
assert is_bearable(FileIO, type[TextIO]) is False # <----- io.FileIO is text IO protocol: ...no? okay, then
assert is_bearable(BinaryIO, type[IO[bytes]]) is True # <- typing.BinaryIO is binary IO protocol: *YUP*
assert is_bearable(TextIO, type[IO[str]]) is True # <----- typing.TextIO is text IO protocol: *YUP*
assert is_bearable(BytesIO, type[BinaryIO]) is False # <-- io.BytesIO is binary IO protocol: ...no? we sighGenerics parametrized by parameter specifications and one or more other arbitrary child type hints. @beartype 0.23.0 now supports user-defined PEP 484- or 585-compliant generics (e.g., typing.Generic subclasses) and PEP 544-compliant protocols (i.e., typing.Protocol subclasses) parametrized by PEP 612-compliant parameter specifications (i.e., typing.ParamSpec objects) followed by one or more other arbitrary child type hints. No one read this far. No one. @beartype will post a meme of a cat wearing a sailor outfit should the prior two sentences prove false. But they won't. That's how depressingly boring this feature is:
from beartype import beartype
from typing import Generic, ParamSpec, TypeVar
P = ParamSpec('P')
R = TypeVar('R')
class Gen(Generic[P, R]): ...
@beartype
def so_generic_so_boring() -> Gen[P, S]: # <-- nobody knows what this means. nobody.
return Gen()
so_generic_so_boring() # <-- descriptive name is proscriptive. what that even mean!?tuple[..., typing.Unpack[tuple[...]]. @beartype 0.23.0 now supports sugar-free backward-compatible tuple type hint unpacking of the form tuple[..., typing.Unpack[tuple[...]] standardized by PEP 646 – the only typing standard that exhausts bald men so fully they give up partway before risking further hair loss:
from beartype import beartype
from typing import Unpack
@beartype
def muh_func_no_idea_bro(x: int) -> (
tuple[int, Unpack[tuple[int, ...]]]): # <-- what the... what does this even mean!?
ls = [i for i in range(x)]
return x, *ls
muh_func_no_idea_bro(5) # <-- i accept things i don't understandtype[typing.Annotated[cls, ...]]. @beartype 0.23.0 now supports PEP 484- and 585-compliant type[...] subclass type hints subscripted by PEP 593-compliant Annotated[cls, ...] child type hints subscripted by... uh, classes. Who even does stuff like this!? Oh, right. NumPy pymaster @jorenham (Joren Hammudoglu). Dude's right about everything. If it's for NumPy, it can't be wrong:
from beartype.door import die_if_unbearable
from beartype.vale import Is
from typing import Annotated
# My eyes may be bleeding, but they bleed for NumPy. It's for data science.
# The eyes are a small sacrifice, Boo.
die_if_unbearable(
str, # <-- this is easy. i get this.
type[Annotated[str, Is[lambda text: len(text) > 30]]], # <-- ...uh...
)Third-party stuff. @beartype supports even more hawt third-party jibberish that I barely understand, including:
coverage command and package that fuels QA everywhere! Previously, Coverage.py and beartype.claw import hooks hated each other. Now, they don't. BFFL status has been restored. CI friends are the best friends. Incidentally, this was pure Hell to get working. You know the kind of Hell. That kind. There are a billion metal bands and albums named "Hell." We've all listened to every single one. Still didn't help. Coverage.py hating beartype.claw took months to resolve. Even when I thought I'd resolved it, I still hadn't. Hell: "When Coverage.py beats beartype.claw up on the way to the water cooler." 🫂markdown-exec! Executable code in Markdown blocks, huh? Nothing could possibly go wrong here. 🥹conf.py scripts. We do not talk about Sphinx here. <-- you get no emoji, sphinxnumpy.typing.NDArray[...] type hints were refactored from PEP 484-compliant generics into PEP 695-compliant type aliases. That means something. Possibly even to me.
@beartype 0.23.0: brought to you by the only catgirl meme suitable for work
@beartype 0.23.0 is the heroic byproduct of open-source volunteerism. For the first time, people and people-like LLMs who are not me did something. They did a lot of something. All prior releases were pretty much the one-bald-man @leycec show. 😮💨
With @beartype 0.23.0, that's begun changing. Finally. Praise be to Anthropic and OpenAI for they have released me from QA bondage. Sounds weird when I put it like that... Maybe I shouldn't put it like that. Oh, well. Too late. We're running with this uncensored changelog as is! No edits. Only half-truths, rictus grins, and nail-biting anxiety.
@beartype 0.23.0 would not be here without:
beartype.door.TypeHint API. beartype.door.TypeHint is the backbone for both Plum-based multiple dispatch and @beartype's own public is_subhint() tester. Stabilizing TypeHint thus stabilizes both Plum and @beartype itself. Thank you a metric tensor, @nstarman! Your sacrifice is a noble example to us all. The human propensity for masochism is legendary throughout the multiverse. @nstarman's came at a cost. A cost @beartype was willing to pay. 😂pytest-beartype. pytest-beartype matters to... uh, 25 people, huh? 25 people out of 9 billion, huh? That's statistics for you. It was hard to make humans care about a QA tool stacked on a QA tool, but 25 humans managed. We salute The High 25. Thank you a starry-eyed emoji, @adamtheturtle! You demolished your sanity for us all. 🤩
@beartype 0.23.0: when you want to beat a bed while crying, think of them
@beartype 0.23.0 had to get out tonight. Python was at stake. QA, which is always quietly on fire, would've caught on even more fire. Therefore, this changelog sucks even more than it would've on a good Friday. It's a tiny fragment of what @beartype 0.23.0 is capable of. But that's fine. Because, ultimately, what @beartype 0.23.0 is capable of is not destroying your codebase.
Sometimes, not destroying your codebase is all that matters. 👍
@beartype 0.23.0: when two ugly pancakes with arms collide, a QA baby is born
warn_if_beartype_claw_inactive(): You Seriously Wanna Call This FunctionPython's burgeoning import hook ecosystem has basically broken down. It never worked all that well to begin with. Now, it increasingly doesn't work at all. First, the bad news, bears. The tl;dr is this:
beartype.claw import hooks are silently ignored whenever a PyInstaller, jaxtyping, or typeguard import hook is used anywhere in the current Python process.Yeah. We know. This isn't just rough. This is abrasively cataclysmic. Let's talk about why this is happening.
Currently, beartype.claw import hooks may be silently overridden and thus disabled under various common conditions. When this occurs, @beartype will silently fail to apply beartype.claw-based runtime type-checking to affected third-party packages and modules. This means your packages and modules, because you are reading this and now frowning. Python app stacks affected by this include any that either:
beartype.claw. Not much we can do about that. Please complain to PyInstaller itself. Openly weep like this to make them feel bad: 😭jaxtyping. If you currently use jaxtyping import hooks, consider switching to @acecchini's third-party bearshape package. bearshape cleanly integrates with @beartype, supports basically everything jaxtyping supports, and even comes with a more Pythonic syntax that looks suspiciously (but welcomely) like standard typing type hint syntax. 👏 👋 👏typeguard. If you currently also use typeguard import hooks, I have no good advice at the moment. "Please seriously don't do that," is the best I can offer at the moment. @beartype 0.24.0 will fix these incompatibilities once and for all. Until then, @beartype weeps for Python's broken import hook ecosystem. 😿That's the bad news. This is happening because Python lacks standards governing interoperability between competing third-party import hooks. No new standards that could remedy this situation appea
Note truncated.
FEATURE FREEZE goes "brrr." @beartype 0.23.0rc2 is the final word in this interminable release cycle. It ends now. @beartype 0.23.0 lands next Wednesd
FEATURE FREEZE goes "brrr." @beartype 0.23.0rc2 is the final word in this interminable release cycle. It ends now. @beartype 0.23.0 lands next Wednesday (September 30th), a day before CPython 3.15.0 itself lands. For the next week, the @beartype issue tracker is frozen in time like a QA Encino Man. No new features will be resolved. No new issues will be fixed (unless they're the QA equivalent of the Deathly Hallows, in which case we all cry). One more time, we gonna celebrate:
# Via "pip", the once-great venerable master packager now fallen on hard times:
$ pip install --upgrade --pre beartype # <-- you go, pipe-smoking pip
# Via "uv", the plucky upstart spiky-haired kid wielding a sword larger than its body:
$ uv pip install --upgrade --pre beartype # <-- when you no longer have the strength to care about lock files
# Via "conda", the corporate scientist in casual lab attire who wants to be your buddy, pal:
$ conda config --add channels conda-forge # <-- where did python packaging go wrong?
$ conda install conda-forge::beartype # <-- it all seemed so simple, once.
<sup>Flying socker boy: @beartype 0.23.0rc2. Lamb: your codebase. Soccer ball: your bugs.</sup>
@beartype 0.23.0rc2 knows that no one is laughing anymore. You've had your fill of this release cycle! Frankly, so have we. An entire year of only crushing bugs has taken its toll on many receding hairlines. The reason there are no new features in @beartype 0.23.0 is the same reason I have no hair. When your younger self writes 100,000 lines of buggy code without testing anything, your older self is guaranteed to suffer. Don't do what the young @leycec did, people. Upgrade to @beartype 0.23.0 instead and let something else crush your bugs for once.
@beartype 0.23.0rc2 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.23.0rc2 resolves a variety of compatibility issues for both Plum and CrossHair users. Other downstream dependencies leveraging our public beartype.door.TypeHint API are also likely to benefit.
Everyone else may promptly fall asleep. These are not the QA droids you're looking for. :joy_cat: -> :sob:
<sup>sleeping in a burned out coliseum doesn't mean you've hit a new low... does it?</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:
@t20100. @samuelstevens. That's it. Let us now admire a bipedal Latin tortoise.
<sup>your life after installing @beartype 0.23.0rc2</sup>
@beartype 0.23.0rc1 plummets off the seemingly insurmountable cliff of the @beartype 0.23.0 release cycle and into your unwelcoming lap. No one cares
@beartype 0.23.0rc1 plummets off the seemingly insurmountable cliff of the @beartype 0.23.0 release cycle and into your unwelcoming lap. No one cares anymore. @beartype 0.23.0 just needs to be released already. I know. You know. Even Claude knows. But... a pleasing number of regressions, issues, and other grim observables have been crushed since the last @beartype 0.23.0rc0 over a month ago. To prevent @beartype from destroying PyTorch, FastMCP, and everything Claude cares about, I ask you to walk with the @beartype 0.23.0 release cycle one last time – and:
# Via "pip", the once-great venerable master packager now fallen on hard times:
$ pip install --upgrade --pre beartype # <-- you go, pipe-smoking pip
# Via "uv", the plucky upstart spiky-haired kid wielding a sword larger than its body:
$ uv pip install --upgrade --pre beartype # <-- when you no longer have the strength to care about lock files
# Via "conda", the corporate scientist in casual lab attire who wants to be your buddy, pal:
$ conda config --add channels conda-forge # <-- where did python packaging go wrong?
$ conda install conda-forge::beartype # <-- it all seemed so simple, once.
<sup>Flying socker boy: @beartype 0.23.0rc1. Lamb: your codebase. Soccer ball: your bugs.</sup>
@beartype 0.23.0rc1 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.23.0rc1 had to get out tonight. Python was at stake. Yet again. I was supposed to type about all of the awesome changes featured in this new release. Instead, I'll be lucky to get this out before I pass out on the keyboard. Therefore, I present a flying space turtle.
<sup>Flying space turtle: @beartype 0.23.0rc1. Missiles: your bugs.</sup>
0.23.0rc1: It's Finally Thread-Safe! Oh, My Gosh! :open_mouth:@beartype is now officially thread-safe. All known thread-safety issues across the entire codebase have been resolved. Of course, everyone thought @beartype was already thread-safe all this time. Right? Didn't you?
Yeah. So did I. In anticipation of our glorious GIL-free future, I've been synchronizing everything in @beartype behind threading.Lock and RLock primitives for literally a decade. I thought that was enough. Then users actually started using free-threaded CPython 3.13t and 3.14t builds. Turns out... that wasn't enough.
Now, it is. Probably. Over the course of the last several months, I've gone hard on thread synchronization throughout the @beartype codebase. I locked everything that could be locked. Then I locked some more. Now, the entire codebase is one gigantic space lock reading:
"Threads: Enter One at a Time, Leave Your Shoes at the Door, and Don't Forget to Wash Your Hands. Offending Threads Will Be Asked to Groom @leycec's Cats Until They No Longer Puke Up Big Hairballs."
<sup>that feeling when you see another unlocked global in a private submodule nested five subdirectories down</sup>
beartype.door.TypeHint: It No Longer SucksOur object-oriented beartype.door.TypeHint API now sucks less than it used to. TypeHint objects now:
TypeHint objects that compare equally now share the same hashes, enabling them to be reliably used as dictionary keys and set members. Previously, that wasn't necessarily the case, which... was bad. Like, real bad. TypeHint objects violated the fundamental soundness principal of hashable objects – preventing their reliable usage as dictionary keys or set members. :vomiting_face:TypeHint objects that compare equal or unequal in one operand ordering (e.g., TypeHint(foo) == TypeHint(bar) is True) now also preserve the same comparison in the reverse ordering (e.g., TypeHint(bar) == TypeHint(foo) is True). Previously, that wasn't necessarily the case. Equality was asymmetric in a small subset of cases. Vomit buckets, please! :vomiting_face: :vomiting_face:typing.Any equality and subhinting. The TypeHint(Any) singleton now compares sanely to all other TypeHint objects. This includes comparisons by both equality and inequality (e.g., TypeHint(Any) == TypeHint(int) is False) as well as subhinting (e.g., TypeHint(Any) <= TypeHint(int), TypeHint(int) <= TypeHint(Any)). Previously... actually, I'm unsure. I don't think @beartype used to compute those relations correctly. But maybe it did? Who can even keep track anymore!? Anyway, @beartype definitely computes those relations correctly now. Unit tests wouldn't lie, would they?TypeHint wrappers and the time costs of reading and writing TypeHint variables (by about ~10%). In practice, you probably won't notice a difference. This is what I spent two days of my precious life on. I encourage you to lie to me. Everyone on your team noticed a difference. Right? Right!? My face exhales. :face_exhaling:Since Plum heavily leverages the TypeHint API, all Plum users really want to upgrade to this pre-release. Eat a plum and feel the "Yum!" :green_apple: = :yum:
<sup>beartype.door.TypeHint: "Fly like a space turtle with jet packs, because you can."</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:
@PhilipVinc. @DUKaige. @@brianstrauch.
<sup>your life after installing @beartype 0.23.0rc1</sup>
> Follow breathtaking new @beartype announcements at [@beartype's official Bluesky account](https://leycec.bsky.social)! I don't post often. I code of
Follow breathtaking new @beartype announcements at @beartype's official Bluesky account! I don't post often. I code often instead. Your feed will remain unpolluted and safe from cat memes... for now. I suddenly want to post lots of cat memes to Bluesky. Why is that? :thinking:
Come live chat with all the @beartype homies at @beartype's official Zulip chat! Don't know how to type hint something? Unsure why @beartype is barfing all over logs? Heckle us in front of a live audience until we collapse or your team finally gets a straight answer. One of these two outcomes is likelier than the other. Zulip: it's like Discord... only less cool. A lot less cool. The UI and UX is frankly incomprehensible. At least Zulip is permissively Apache-licensed GitHub-hosted open-source. I'm not selling this whole Zulip thing, am I? :smiling_face_with_tear:
Come gape, gawk, and gander at @beartype's new official Zensical documentation:
beartype.github.io/beartype! The content may look exactly like @beartype's old unmaintained Sphinx documentation that we don't talk about anymore, but... uh, that's only because looks can be deceiving? Oh, alright. They're exactly the same. That will soon change. That had better soon change. Sphinx makes us "BARF!" like Larry in Rivercity Ransom. Zensical, on the other hand, is the delectable modern successor to Mkdocs. You do not want to know what happened to Mkdocs. Seriously. Don't go down that hole. Thanks so much to brilliant @beartype bro @posita for crushing this one out with his buddy "Claudio". :fist_right: :fist_left:
@beartype now routinely hits 4 million downloads a day. Apparently, that means something. Arbitrary numbers that get bigger matter to small petty bald men like me. It's like real-life suddenly became a hit JRPG – and I am so here for that energy. :joy:
@beartype's GitHub Sponsors have collapsed into a black hole reading: "Nobody likes you, bro." @beartype basically doesn't have any sponsors anymore is what I'm saying. I blame no one but myself. I do the coding thing. I don't do the marketing thing. The results are unsurprising. Pity the Bear by feeding the Bear a dollar for a day. He may not learn to fish like that, but at least he'll be able to buy some fish for the cats. :face_holding_back_tears:
@beartype
0.23.0rc0resolves so many mission-critical issues that everyone really wants to require @beartype0.23.0rc0as a minimum version in theirpyproject.tomlfiles. Save your app stack today before our last stable @beartype0.22.9release tears it down tomorrow. Just:
dependencies = [
...
"beartype >= 0.23.0rc", # <-- pretend @beartype 0.22.9 never existed. that's what we do.
...
]
Protect your calls to
beartype_this_package()against malicious third-party import hooks. Call our new publicbeartype.claw.warn_if_beartype_claw_inactive()function to receive an informative non-fatal warning whenever somebody else stifles yourbeartype.clawimport hooks. If you'd like to dig even deeper into the contentious topic of import hooks that hate each other, consider @Glinte's third-partymetapathologypackage for all your investigatoryimportlibneeds. You tell 'em, @Glinte! Just:
from beartype.claw import beartype_this_package, warn_if_beartype_claw_inactive
beartype_this_package()
warn_if_beartype_claw_inactive() # <-- if the prior line did nothing, at least now you know :(
Type-check NumPy, JAX, PyTorch, and CuPy tensor constraints with @acecchini's third-party
bearshapepackage! It's likejaxtyping, only @beartype-native from the ground-up. Likejaxtyping,bearshaperuntime type-checks tensors across a wide variety of frameworks. Unlikejaxtyping,bearshapecleanly integrates with @beartype.bearshapedoes not stomp all overbeartype.claw-based type-checking. You go,bearshape! Just:
from beartype import beartype
from bearshape import N, C
from bearshape.numpy import F32
@beartype
def normalize(x: F32[N, C]) -> F32[N, C]: # <-- i'm nodding like i understand this
return x / x.sum(axis=1, keepdims=True)
Why are there so many crazy prefatory notes for this release, anyway? Everybody's already exhausted. This changelog hasn't even started yet, has it? :face_exhaling:
<-- your face probably
@beartype 0.23.0rc0 thunders down the road of good QA intentions in a desperate bid to crush all the skittering bugs eating your codebase to the bone. Under its spike-studded wheels of doom stability, @beartype 0.23.0rc0 exposes the fragile arrogance at the heart of trying to do anything crush bugs in Python:
# Via "pip", the once-great venerable master packager now fallen on hard times:
$ pip install --upgrade beartype # <-- you go, pipe-smoking pip
# Via "uv", the plucky upstart spiky-haired kid wielding a sword larger than its body:
$ uv pip install --upgrade beartype # <-- when you no longer have the strength to care about lock files
# Via "conda", the corporate scientist in casual lab attire who wants to be your buddy, pal:
$ conda config --add channels conda-forge # <-- where did python packaging go wrong?
$ conda install conda-forge::beartype # <-- it all seemed so simple, once.
<sup>Right: @beartype 0.23.0rc0. Left: Your codebase. Middle: Your CTO stares dumbfounded.</sup>
@beartype 0.23.0rc0 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.23.0rc0 had to get out tonight. Python was at stake. QA, which is always quietly on fire, would've caught on even more fire. Therefore, this changelog sucks even more than it would've on a good Friday. It's a tiny fragment of what @beartype 0.23.0rc0 is capable of. But that's fine. Because, ultimately, what @beartype 0.23.0rc0 is capable of is not destroying your codebase.
Sometimes, not destroying your codebase is all that matters. :+1:
<sup>@beartype 0.23.0rc0: when two ugly pancakes with arms collide, a QA baby is born</sup>
warn_if_beartype_claw_inactive(): You Seriously Wanna Call This FunctionPython's burgeoning import hook ecosystem has basically broken down. It never worked all that well to begin with. Now, it increasingly doesn't work at all. First, the bad news, bears. The tl;dr is this:
beartype.claw import hooks are silently ignored whenever a PyInstaller, jaxtyping, or typeguard import hook is used anywhere in the current Python process.Yeah. We know. This isn't just rough. This is abrasively cataclysmic. Let's talk about why this is happening.
Currently, beartype.claw import hooks may be silently overridden and thus disabled under various common conditions. When this occurs, @beartype will silently fail to apply beartype.claw-based runtime type-checking to affected third-party packages and modules. This means your packages and modules, because you are reading this and now frowning. Python app stacks affected by this include any that either:
beartype.claw. Not much we can do about that. Please complain to PyInstaller itself. Openly weep like this to make them feel bad: :sob:jaxtyping. If you currently use jaxtyping import hooks, consider switching to @acecchini's third-party bearshape package. bearshape cleanly integrates with @beartype, supports basically everything jaxtyping supports, and even comes with a more Pythonic syntax that looks suspiciously (but welcomely) like standard typing type hint syntax. :clap: :wave: :clap:typeguard. If you currently also use typeguard import hooks, I have no good advice at the moment. "Please seriously don't do that," is the best I can offer at the moment. @beartype 0.24.0 will fix these incompatibilities once and for all. Until then, @beartype weeps for Python's broken import hook ecosystem. :crying_cat_face:That's the bad news. This is happening because Python lacks standards governing interoperability between competing third-party import hooks. No new standards that could remedy this situation appear to be forthcoming in the near future, either. No one cares that Python's import hook ecosystem doesn't work at the moment. Kinda sad.
The good news is that @beartype can resolve most of this situation entirely on its own. A future version of @beartype will do just that. Probably @beartype 0.24.0 in a few months, because this ongoing contention between import hooks is awful. It has to stop. Thus, we are forcing it to stop. Our way. The @beartype way. :muscle: :bear:
The bad bad news is that @beartype isn't doing that at the moment. Until @beartype resolves import hook contention on its side, consider manually calling our new public beartype.claw.warn_if_beartype_claw_inactive() function after calling any beartype.claw import hook (e.g., beartype_this_package()). If somebody else stifled that call without your consent, you'll receive an informative non-fatal warning that could destroy your will to continue coding:
from beartype.claw import beartype_this_package, warn_if_beartype_claw_inactive
beartype_this_package()
warn_if_beartype_claw_inactive() # <-- if the prior line did nothing, at least now you know :(
See also this feature request for a horrifyingly detailed description of a new pseudostandard I just made up to force cooperation between competing third-party import hooks. When you want to feel deranged, you want to read that issue. :laughing: <sup><-- not that funny honestly</sup>
If you'd like to dig even deeper into the contentious topic of import hooks that hate each other, consider @Glinte's third-party metapathology package for all your investigatory importlib needs. You tell 'em, @Glinte! :fist_raised:
<sup>when your right arm refuses to put itself down, you know you should've upgraded to @beartype 0.23.0rc0</sup>
BeartypeConf(is_random=False): Never Do This and No One Gets HurtSo. You want to disable @beartype's default pseudorandom type-checking behaviour, huh? You think you want many things in life – until you finally get what you asked for. Then the monkey's pawl curls. Your codebase dies quietly. You shriek to an uncaring city skyline shortly before the burning helicopter hurtles to the ground:
"Why? Why is this happening!?"
@beartype's default pseudorandom type-checking behaviour is a good thing. You forgot that essential lesson in life. Pseudorandom type-checking dramatically increases the likelihood of catching invalid items in pure-Python containers (e.g., dict, list) before they have a chance to hurtle burning helicopters to the ground.
Sometimes, though, that default behaviour is not a good thing. There is a valid reason for disabling pseudorandom type-checking: test consistency. Want tests to fail consistently, uniformly, and deterministically rather than dissolving into a non-deterministic crapshoot of incoherent fragility? It happens. We understand. Then your tests want to explicitly disable the new BeartypeConf(is_random=False) configuration option as follows:
# In some pytest-driven unit test somewhere that currently hates @beartype...
def test_beartype_haters_gonna_hate() -> None:
from beartype import beartype, BeartypeConf
# Test-specific @beartype decorator performing deterministic type-checking! Ugh.
boring_beartype = beartype(conf=BeartypeConf(is_random=False))
@boring_beartype
def beartype_randomness(can_suck_an_egg: list[str]) -> str:
return can_suck_an_egg[0]
# This assertion is now guaranteed to *ALWAYS* succeed, despite the fact that
# this call semantically violates the type hint annotating the "can_suck_an_egg"
# parameter accepted by the beartype_randomness() function defined above. But
# you don't care anymore, do you? You just want this to pass. Now, it can.
#
# The only cost is sanity. Because nothing means anything anymore. Enjoy.
kinda_awful_honestly = beartype_randomness([
'A string, yo.', b'...totally not a string', 0xFEEDBABE])
assert kinda_awful_honestly == 'A string, yo.'
Sure. It's awful. Sometimes, that's exactly what you need.
BeartypeConf(is_random=False): when you need awful, you need @beartype.
<sup>@beartype 0.23.0rc0: "your single new configuration option fails to impress me"</sup>
OHNOES. It's 2:13AM. An ominous time, if ever there was. I've gotta wrap this thing up quickly while convincing you that I intensely care about this concluding section.
Here's the deal. Forward references? You know, those type hints that are strings referring to an external type or type hint defined somewhere else that you can't import into the current module for specious reasons that are better left undocumented? Those forward references?
...yeah. Prior versions of @beartype only pretended to support forward references. @beartype's previous support for forward references was so slipshod, unreliable, and context-dependent that @beartype basically didn't support forward references. Not really, anyway.
That's why I spent the last six months <sup>why is life like this</sup> completely rewriting @beartype's internal forward reference resolution engine from the ground up. Common uses cases that now reliably work include:
Forward references to arbitrary type hints defined elsewhere. Previously, @beartype only supported forward references to classes. Now, @beartype's supports forward references to literally anything. If it's a valid type hint, you can now refer to it: e.g.,
# In submodule "i_pity.da_foo":
WorstTypeHintEver = 'list[int]' # <-- look i don't know it's late
# In submodule "i_pity.da_bar":
from beartype import beartype
@beartype
def pitiable_func(grovelling_arg: 'i_pity.da_foo.WorstTypeHintEver') -> int:
return grovelling_arg[0]
pitiable_func([0xBABEFACE]) # <-- uh wut
Relative forward references in die_if_unbearable() and is_bearable() calls. Previously, both the die_if_unbearable() and is_bearable() functions prohibited relative forward references (i.e., forward references omitting a module name and thus relative to the current module). Now, die_if_unbearable() and is_bearable() dynamically hunt up the call stack for the calling module calling those functions and intelligently resolve relative forward references against that calling module: e.g.,
from beartype.door import die_if_unbearable
def its_so_late(my_face_is_gonna_fall_off: object) -> None:
die_if_unbearable(
my_face_is_gonna_fall_off,
'SomeClassThatHasntBeenDefinedYet' # <-- relative forward reference! so cool
)
class SomeClassThatHasntBeenDefinedYet: ...
# This totally works now. Yay! What a lame example, though. Can we all agree this
# example was lame? We can. I don't mind someone rubbing that the truth into my soul.
its_so_late(SomeClassThatHasntBeenDefinedYet())
Heaps of other forward reference stuff, too. It's late. We're done.
Peace out, wonderful bear family! We'll excrete a heap more text that actually means something for the official stable @beartype 0.23.0 mic drop. Until then, have a wonderful remainder of your summer – and may the QA be with you always. :heart_hands: :smiling_face_with_three_hearts: :revolving_hearts:
<sup>Robot Chicken says: "OMG @beartype 0.23.0rc0! PEACE OUT Y'ALL! I'M A ROBOT CHICKEN!!!!"</sup>
Almost forgot. @beartype 0.23.0rc0 also officially supports Python 3.15. That's right, y'all. As of @beartype 0.23.0rc0, Robot Chicken ain't the only one who can use the word "y'all" anymore, y'all.
Python 3.15: "You want the JIT speed it bringin'."
<sup>@beartype 0.23.0rc0: when it cross its arms, you just know all bugs is dead</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. @Glinte. @wesselb. @jorenham. @JWCS. @adamtheturtle. @tusharsadhwani. @TeamSpen210. @bitranox. @ilyapoz. @benoit74. @hmgaudecker. @nstarman. @Gattocrucco. @javi-linx. @tseaver. @kdeldycke. @gotmax23. @black-snow. @DetachHead. @asitstands. @jeertmans. @abhinand-c. @mzealey. @ITcarrot. @danielkovtun. @ddorian. @riesentoaster. @sean-roelofs-ai. Heroes among us.
<sup>@beartype 0.23.X dev cycle: still accursed after all these cat memes.</sup>
@beartype 0.22.9 celebrates one million @beartype downloads a day! We wanted to rent out a loft warehouse space, flip a dry ice machine off Ebay for p
@beartype 0.22.9 celebrates one million @beartype downloads a day! We wanted to rent out a loft warehouse space, flip a dry ice machine off Ebay for pennies, shadow-drop DJ Lorien Testard, invite all our GitHub homies, and get down and funky with this QA quinceañera. It didn't happen. I released instead. The memories we might have made are only another patch release in the 0.22.X dev cycle. Bear friends, it's your time to shine tonight:
# Via "pip", the once-great venerable master packager now fallen on hard times:
$ pip install --upgrade beartype # <-- you go, pipe-smoking pip
# Via "uv", the plucky upstart spiky-haired kid wielding a sword larger than its body:
$ uv pip install --upgrade beartype # <-- when you no longer have the strength to care about lock files
# Via "conda", the corporate scientist in casual lab attire who wants to be your buddy, pal:
$ conda config --add channels conda-forge # <-- where did python packaging go wrong?
$ conda install conda-forge::beartype # <-- it all seemed so simple, once.
@beartype 0.22.9: "Wave your keyboards in the air like those bugs don't care."
<sup>one million downloads a day says you can't stop this party</sup>
@beartype 0.22.9 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.9 brings official support for... wait. PyInstaller? Hasn't @beartype supported PyInstaller since the beginning? Yeah. We thought so too. Then Meta was all like: "Oh no you don't, @beartype." :joy:
@beartype has officially supported competing products like Nuitka for years. Now PyInstaller joins the ranks. But it's not just PyInstaller. @beartype 0.22.9 should also resolve any similar pending issues with other app bundling frameworks like... uhh, Briefcase? No idea, honestly. That's untested wishful thinking. The very best kind.
@beartype 0.22.9: When you realize a small part of you still cares about desktop apps.
<sup>Your bundled app moments after being packaged with @beartype. It's... not good.</sup>
ty: It's So Fast We Barely Support It@beartype 0.22.9 also brings unofficial and mostly just superficial support for Astral's ty, the newest member of the Astral family and Python's latest static type-checking darling. Thanks so much to long-standing bear warrior @Glinte for his masterful compatibility work here.
@beartype should no longer fall down on its face when confronted with ty. Should. Why does that word feel like it's doing so much heavy lifting here!? Since @beartype already officially supports both mypy and pyright, extending that with official support for ty as well is... unlikely. We're out of bandwidth. The gas tank is empty. Red warning lights emit a blinding glare. My leather-tanned face is one giant frown wrinkle. That said...
@beartype doesn't intend to do ty dirty. We might not like that there's yet another static type-checker in an all-too crowded field of indistinguishable lookalikes all yelling and shouting at the top of their lungs. Okay. We definitely don't like that. But we also can't do anything about that. If you like ty, @beartype will do its best to like ty. If you hit any snags at the intersection of ty and @beartype, just drop us a line. We'll try not to complain. Sure. We will anyway. We all know that. But at least we've made a promise we can't possibly keep.
@beartype 0.22.9: It promises things.
<sup>When your static type-checker sees @beartype for the first time.</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:
@zbowling. @adamtheturtle. @Glinte. @JWCS. @bitranox. Heroes among us.
<sup>@beartype 0.22.X dev cycle: it may be accursed, but at least it's cute.</sup>
@beartype 0.22.9 celebrates one million @beartype downloads a day! We wanted to rent out a loft warehouse space, flip a dry ice machine off Ebay for pennies, shadow-drop DJ Lorien Testard, invite all our GitHub homies, and get down and funky with this QA quinceañera. It didn't happen. I released instead. The memories we might have made are only another patch release in the 0.22.X dev cycle. Bear friends, it's your time to shine tonight:
# Via "pip", the once-great venerable master packager now fallen on hard times:
$ pip install --upgrade beartype # <-- you go, pipe-smoking pip
# Via "uv", the plucky upstart spiky-haired kid wielding a sword larger than its body:
$ uv pip install --upgrade beartype # <-- when you no longer have the strength to care about lock files
# Via "conda", the corporate scientist in casual lab attire who wants to be your buddy, pal:
$ conda config --add channels conda-forge # <-- where did python packaging go wrong?
$ conda install conda-forge::beartype # <-- it all seemed so simple, once.@beartype 0.22.9: "Wave your keyboards in the air like those bugs don't care."
one million downloads a day says you can't stop this party
@beartype 0.22.9 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.
The Masters of Fintech and Lifted Tides. That's who.
@beartype 0.22.9 brings official support for... wait. PyInstaller? Hasn't @beartype supported PyInstaller since the beginning? Yeah. We thought so too. Then Meta was all like: "Oh no you don't, @beartype." 😂
@beartype has officially supported competing products like Nuitka for years. Now PyInstaller joins the ranks. But it's not just PyInstaller. @beartype 0.22.9 should also resolve any similar pending issues with other app bundling frameworks like... uhh, Briefcase? No idea, honestly. That's untested wishful thinking. The very best kind.
@beartype 0.22.9: When you realize a small part of you still cares about desktop apps.
Your bundled app moments after being packaged with @beartype. It's... not good.
ty: It's So Fast We Barely Support It@beartype 0.22.9 also brings unofficial and mostly just superficial support for Astral's ty, the newest member of the Astral family and Python's latest static type-checking darling. Thanks so much to long-standing bear warrior @Glinte for his masterful compatibility work here.
@beartype should no longer fall down on its face when confronted with ty. Should. Why does that word feel like it's doing so much heavy lifting here!? Since @beartype already officially supports both mypy and pyright, extending that with official support for ty as well is... unlikely. We're out of bandwidth. The gas tank is empty. Red warning lights emit a blinding glare. My leather-tanned face is one giant frown wrinkle. That said...
@beartype doesn't intend to do ty dirty. We might not like that there's yet another static type-checker in an all-too crowded field of indistinguishable lookalikes all yelling and shouting at the top of their lungs. Okay. We definitely don't like that. But we also can't do anything about that. If you like ty, @beartype will do its best to like ty. If you hit any snags at the intersection of ty and @beartype, just drop us a line. We'll try not to complain. Sure. We will anyway. We all know that. But at least we've made a promise we can't possibly keep.
@beartype 0.22.9: It promises things.
When your static type-checker sees @beartype for the first time.
...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:
@zbowling. @adamtheturtle. @Glinte. @JWCS. @bitranox. Heroes among us.
@beartype 0.22.X dev cycle: it may be accursed, but at least it's cute.
@beartype 0.22.8. It's happening. Yet, it shouldn't be happening. This is the corrupt timeline we live on:
@beartype 0.22.8. It's happening. Yet, it shouldn't be happening. This is the corrupt timeline we live on:
# Via "pip", the once-great venerable master packager now fallen on hard times:
$ pip install --upgrade beartype # <-- you go, pipe-smoking pip
# Via "uv", the plucky upstart spiky-haired kid wielding a sword larger than its body:
$ uv pip install --upgrade beartype # <-- when you no longer have the strength to care about lock files
# Via "conda", the corporate scientist in casual lab attire who wants to be your buddy, pal:
$ conda config --add channels conda-forge # <-- where did python packaging go wrong?
$ conda install conda-forge::beartype # <-- it all seemed so simple, once.
@beartype 0.22.6 broke synchronous generator returns. @beartype 0.22.8 is unbreaking what its younger sibling brazenly broke. The recklessness of youth, huh? Generator returns, huh? Fandango cares about synchronous generator returns. Surely, they can't be the only ones!? Seems like they're the only ones. Is there anything weirder than retrieving a return value by stripping the value instance variable out of a StopIteration exception caught while manually iterating a synchronous generator one iteration past its last valid yield? No? Just me? Who designs APIs like that, anyway? I can just imagine the internal discussion thread speccing this cruft out:
"So. Uhh. Your API returns values by bolting them onto the side of builtin exceptions implicitly raised when your iterator is exhausted, huh? You can't even access those return values if you iterate over your iterator with
forloops, huh? You've got to manually iterate your iterator withnext()calls, huh? Even though that's infeasible in the general case, huh? Sounds good to me. It's in."
@beartype 0.22.8 had better be the last patch release of the 0.22.X dev cycle. Overlord Ainz Ooal Gown, we summon you to complete the dark ritual! End this endless cycle of bug death and rebirth... once and for all.
<sup>@beartype 0.22.8: you know that feeling when a skeletal demon lord raises his eldritch staff of oblivion in triumphant hubris? yeah. this is like that.</sup>
@beartype 0.22.8 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>
...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:
@henryhchchc. @riesentoaster. @adamtheturtle. @pablovela5620. @crypdick. @Glinte. @JWCS. @bitranox. Heroes among us.
<sup>@beartype 0.22.X dev cycle: bye now tnx so much for coming. no, reallys. @leycec means it this time. reallys!</sup>
@beartype 0.22.8. It's happening. Yet, it shouldn't be happening. This is the corrupt timeline we live on:
# Via "pip", the once-great venerable master packager now fallen on hard times:
$ pip install --upgrade beartype # <-- you go, pipe-smoking pip
# Via "uv", the plucky upstart spiky-haired kid wielding a sword larger than its body:
$ uv pip install --upgrade beartype # <-- when you no longer have the strength to care about lock files
# Via "conda", the corporate scientist in casual lab attire who wants to be your buddy, pal:
$ conda config --add channels conda-forge # <-- where did python packaging go wrong?
$ conda install conda-forge::beartype # <-- it all seemed so simple, once.@beartype 0.22.6 broke synchronous generator returns. @beartype 0.22.8 is unbreaking what its younger sibling brazenly broke. The recklessness of youth, huh? Generator returns, huh? Fandango cares about synchronous generator returns. Surely, they can't be the only ones!? Seems like they're the only ones. Is there anything weirder than retrieving a return value by stripping the value instance variable out of a StopIteration exception caught while manually iterating a synchronous generator one iteration past its last valid yield? No? Just me? Who designs APIs like that, anyway? I can just imagine the internal discussion thread speccing this cruft out:
"So. Uhh. Your API returns values by bolting them onto the side of builtin exceptions implicitly raised when your iterator is exhausted, huh? You can't even access those return values if you iterate over your iterator with
forloops, huh? You've got to manually iterate your iterator withnext()calls, huh? Even though that's infeasible in the general case, huh? Sounds good to me. It's in."
@beartype 0.22.8 had better be the last patch release of the 0.22.X dev cycle. Overlord Ainz Ooal Gown, we summon you to complete the dark ritual! End this endless cycle of bug death and rebirth... once and for all.
@beartype 0.22.8: you know that feeling when a skeletal demon lord raises his eldritch staff of oblivion in triumphant hubris? yeah. this is like that.
@beartype 0.22.8 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.
The Masters of Fintech and Lifted Tides. That's who.
...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:
@henryhchchc. @riesentoaster. @adamtheturtle. @pablovela5620. @crypdick. @Glinte. @JWCS. @bitranox. Heroes among us.
@beartype 0.22.X dev cycle: bye now tnx so much for coming. no, reallys. @leycec means it this time. reallys!
@beartype 0.22.7 descends like an owl with sorta unsettling black eyes devoid of pupils, majestic wings aloft on the winds of QA. *Do not be alarmed.*
@beartype 0.22.7 descends like an owl with sorta unsettling black eyes devoid of pupils, majestic wings aloft on the winds of QA. Do not be alarmed. Actually, isn't that when you should be most alarmed? When somebody says, "Do not be alarmed"!? The italicization isn't helping, either. But this will:
# Via "pip", the once-great venerable master packager now fallen on hard times:
$ pip install --upgrade beartype # <-- you go, pipe-smoking pip
# Via "uv", the plucky upstart spiky-haired kid wielding a sword larger than its body:
$ uv sync beartype # <-- @Glinte said it, so it must be true
# Via "conda", the corporate scientist in casual lab attire who wants to be your buddy, pal:
$ conda config --add channels conda-forge # <-- where did python packaging go wrong?
$ conda install conda-forge::beartype # <-- it all seemed so simple, once.
@beartype 0.22.7 is the last patch release of the 0.22.X dev cycle. That was a lie. Fortunately, seductive lies aren't a problem here at @beartype. If we want to hear it, it can't be bad. This release brings big:
0.22.7. :spider_web: + :bear: = :safety_pin:async yield from expression at future-async-yield-from was hugely inspiring. If you're into mutating Python into misshapen forms through the cosmic horrors of forbidden AST transformations, <sup>...who isn't? am i right? i'm right</sup> check out @rbroderi's work. He's up to no good, which is the best kind. :hugs: :people_hugging:That's it. That's all we've got. But you don't even want to know the things we did, the places we went, the behaviour we regret, to make Gradio + @beartype happen. If Gradio means nothing to you, we've got nothing but memes for you.
@beartype should now support all popular Python frameworks. If you (or a codebase you love) know of any Python packages, modules, APIs, or other services that @beartype does not support, please drop us a line on the issue tracker. We'll drop what we're doing <sup>video games. it's always video games.</sup> and "immediately" resolve that for your heroic team.
Until then, video games await. Let's get those memes started!
<sup>the more you stare at this, the more your brain sees</sup>
@beartype 0.22.7 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>
...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:
@adamtheturtle. @pablovela5620. @crypdick. @Glinte. @JWCS. @bitranox. Heroes among us.
<sup>@beartype 0.22.X dev cycle: bye now tnx so much for coming</sup>
@beartype 0.22.7 descends like an owl with sorta unsettling black eyes devoid of pupils, majestic wings aloft on the winds of QA. Do not be alarmed. Actually, isn't that when you should be most alarmed? When somebody says, "Do not be alarmed"!? The italicization isn't helping, either. But this will:
# Via "pip", the once-great venerable master packager now fallen on hard times:
$ pip install --upgrade beartype # <-- you go, pipe-smoking pip
# Via "uv", the plucky upstart spiky-haired kid wielding a sword larger than its body:
$ uv sync beartype # <-- @Glinte said it, so it must be true
# Via "conda", the corporate scientist in casual lab attire who wants to be your buddy, pal:
$ conda config --add channels conda-forge # <-- where did python packaging go wrong?
$ conda install conda-forge::beartype # <-- it all seemed so simple, once.@beartype 0.22.7 is the last patch release of the 0.22.X dev cycle. That was a lie. Fortunately, seductive lies aren't a problem here at @beartype. If we want to hear it, it can't be bad. This release brings big:
0.22.7. 🕸️ + 🐻 = 🧷async yield from expression at future-async-yield-from was hugely inspiring. If you're into mutating Python into misshapen forms through the cosmic horrors of forbidden AST transformations, ...who isn't? am i right? i'm right check out @rbroderi's work. He's up to no good, which is the best kind. 🤗 🫂That's it. That's all we've got. But you don't even want to know the things we did, the places we went, the behaviour we regret, to make Gradio + @beartype happen. If Gradio means nothing to you, we've got nothing but memes for you.
@beartype should now support all popular Python frameworks. If you (or a codebase you love) know of any Python packages, modules, APIs, or other services that @beartype does not support, please drop us a line on the issue tracker. We'll drop what we're doing video games. it's always video games. and "immediately" resolve that for your heroic team.
Until then, video games await. Let's get those memes started!
the more you stare at this, the more your brain sees
@beartype 0.22.7 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.
The Masters of Fintech and Lifted Tides. That's who.
...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:
@adamtheturtle. @pablovela5620. @crypdick. @Glinte. @JWCS. @bitranox. Heroes among us.
@beartype 0.22.X dev cycle: bye now tnx so much for coming
@beartype 0.22.6 sidles up to your door at 11:20PM with a steaming hot-out-of-the-oven delivery of... *wait.* This isn't pizza. Where's the pizza, del
@beartype 0.22.6 sidles up to your door at 11:20PM with a steaming hot-out-of-the-oven delivery of... wait. This isn't pizza. Where's the pizza, delivery bear? Delivery bear growls, "There is no pizza." You feel uneasy. Maybe asking delivery bear awkward questions as it loiters outside your door under the pale moonlight isn't a choice you'd make again. You accept the misshapen bundle cradled gently in its paws. You know what it is without even looking. It's all so eerily familiar:
# Via "pip", the once-great venerable master packager now fallen on hard times:
$ pip install --upgrade beartype # <-- you go, pipe-smoking pip
# Via "uv", the plucky upstart spiky-haired kid wielding a sword larger than its body:
$ uv lock --upgrade-package beartype # <-- you do what you need to do, ultraviolet radiation
# Via "conda", the corporate scientist in casual lab attire who wants to be your buddy, pal:
$ conda config --add channels conda-forge # <-- where did python packaging go wrong?
$ conda install conda-forge::beartype # <-- it all seemed so simple, once.
@beartype 0.22.6 is the patch release you can trust. Finally. <sup>caveats may apply. <sup>caveats may destroy your app stack mere minutes after upgrading.</sup></sup>
<sup>Your based Gradio-based ML-LLM-AI web app at https://moneybags.ai mere minutes after upgrading.</sup>
@beartype 0.22.5 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.6 delivers almost full-blown Gradio compatibility. If the adverb "almost" wasn't doing so much heavy lifting in the prior sentence, we would've punctuated that sentence with an exclamation point. Do not be alarmed by the lack of an exclamation point. @beartype 0.22.6 doesn't destroy your app stack. At 11:20PM, it's the small things.
@beartype 0.22.6 preserves inspect.isgeneratorfunction()-ness across @beartype-decorated synchronous generator functions. Gradio needs this, apparently. Previously, the standard inspect.isgeneratorfunction() returned False when passed @beartype-decorated generators. Now, inspect.isgeneratorfunction() returns True. Pretend you understand what this means even as you nod off in the La-Z-Bear-Boy in the foyer that smells faintly of shaving cream:
# Been there. Done that. Bought the bear shirt.
>>> from beartype import beartype
>>> from collections.abc import Iterable
>>> from inspect import isgeneratorfunction
### Synchronous generator! Excitement intensifies! WHY AM I SHOUTING!?!?!?!?!?!?!?!?
>>> @beartype
... def congenial_generator(parboiled_parameter: str | None) -> Iterable[str | None]:
... yield parboiled_parameter
# Prove that @beartype 0.22.6 actually did something.
>>> isgeneratorfunction(congenial_generator)
True # <-- that's it? that's all you've got?
@beartype 0.22.6 does not, unfortunately, preserve inspect.isasyncgenfunction()-ness across @beartype-decorated asynchronous generator functions. Gradio needs that, too. But everyone who's anyone says that's impossible. When you ask the impossible of @beartype, do not be surprised when @beartype fillets a salmon on your desk instead.
And... that's all we've got. It ain't much. It ain't how the QA was won. But that'll do, bear. That'll do.
<sup>@beartype 0.22.6: people smile when you shoot arrows through your hat</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:
@adamtheturtle. @pablovela5620. @crypdick. @Glinte. @JWCS. @bitranox. Heroes among us.
<sup>@beartype and Gradio. You can feel the smug.</sup>
@beartype 0.22.6 sidles up to your door at 11:20PM with a steaming hot-out-of-the-oven delivery of... wait. This isn't pizza. Where's the pizza, delivery bear? Delivery bear growls, "There is no pizza." You feel uneasy. Maybe asking delivery bear awkward questions as it loiters outside your door under the pale moonlight isn't a choice you'd make again. You accept the misshapen bundle cradled gently in its paws. You know what it is without even looking. It's all so eerily familiar:
# Via "pip", the once-great venerable master packager now fallen on hard times:
$ pip install --upgrade beartype # <-- you go, pipe-smoking pip
# Via "uv", the plucky upstart spiky-haired kid wielding a sword larger than its body:
$ uv lock --upgrade-package beartype # <-- you do what you need to do, ultraviolet radiation
# Via "conda", the corporate scientist in casual lab attire who wants to be your buddy, pal:
$ conda config --add channels conda-forge # <-- where did python packaging go wrong?
$ conda install conda-forge::beartype # <-- it all seemed so simple, once.@beartype 0.22.6 is the patch release you can trust. Finally. caveats may apply. caveats may destroy your app stack mere minutes after upgrading.
Your based Gradio-based ML-LLM-AI web app at https://moneybags.ai mere minutes after upgrading.
@beartype 0.22.5 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.
The Masters of Fintech and Lifted Tides. That's who.
@beartype 0.22.6 delivers almost full-blown Gradio compatibility. If the adverb "almost" wasn't doing so much heavy lifting in the prior sentence, we would've punctuated that sentence with an exclamation point. Do not be alarmed by the lack of an exclamation point. @beartype 0.22.6 doesn't destroy your app stack. At 11:20PM, it's the small things.
@beartype 0.22.6 preserves inspect.isgeneratorfunction()-ness across @beartype-decorated synchronous generator functions. Gradio needs this, apparently. Previously, the standard inspect.isgeneratorfunction() returned False when passed @beartype-decorated generators. Now, inspect.isgeneratorfunction() returns True. Pretend you understand what this means even as you nod off in the La-Z-Bear-Boy in the foyer that smells faintly of shaving cream:
# Been there. Done that. Bought the bear shirt.
>>> from beartype import beartype
>>> from collections.abc import Iterable
>>> from inspect import isgeneratorfunction
### Synchronous generator! Excitement intensifies! WHY AM I SHOUTING!?!?!?!?!?!?!?!?
>>> @beartype
... def congenial_generator(parboiled_parameter: str | None) -> Iterable[str | None]:
... yield parboiled_parameter
# Prove that @beartype 0.22.6 actually did something.
>>> isgeneratorfunction(congenial_generator)
True # <-- that's it? that's all you've got?@beartype 0.22.6 does not, unfortunately, preserve inspect.isasyncgenfunction()-ness across @beartype-decorated asynchronous generator functions. Gradio needs that, too. But everyone who's anyone says that's impossible. When you ask the impossible of @beartype, do not be surprised when @beartype fillets a salmon on your desk instead.
And... that's all we've got. It ain't much. It ain't how the QA was won. But that'll do, bear. That'll do.
@beartype 0.22.6: people smile when you shoot arrows through your hat
...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:
@adamtheturtle. @pablovela5620. @crypdick. @Glinte. @JWCS. @bitranox. Heroes among us.
@beartype and Gradio. You can feel the smug.
@beartype 0.22.5 does stuff. *Uhhh.* Wait. Why are we releasing yet another @beartype 0.22.x patch within the span of ten seconds? We were just here.
@beartype 0.22.5 does stuff. Uhhh. Wait. Why are we releasing yet another @beartype 0.22.x patch within the span of ten seconds? We were just here. We already released @beartype 0.22.4 a week ago. Wasn't that good enough!? I... I guess not. Turns out ${PYTHONOPTIMIZE} support has been busted in @beartype for literally years. Probably decades. Nobody cared – until somebody cared. I blame only myself despite wanting to point the finger at somebody else. Anybody else. I'll take anybody. Let's start over.
@beartype 0.22.5 valiantly arises from the ashes of our issue tracker like a burning phoenix on fire!!!! You can't stop this:
# Via "pip", the once-great venerable master packager now fallen on hard times:
$ pip install --upgrade beartype # <-- you go, pipe-smoking pip
# Via "uv", the plucky upstart spiky-haired kid wielding a sword larger than its body:
$ uv lock --upgrade-package beartype # <-- you do what you need to do, ultraviolet radiation
@beartype 0.22.5 stoically puts on the sunglasses so you don't have to.
<sup>The sky is blue and I have hair again.</sup>
@beartype 0.22.5 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.5 is a patch release that guarantees compatibility with Python optimization. Both the @beartype decorator and beartype.claw import hooks now silently reduce to noops (i.e., do nothing rather than type-checking everything) when users:
-O options to the Python interpreter (e.g., python -O worldshattering_app_shatters_world_accidentally.py).${PYTHONOPTIMIZE} environment variable to a positive integer (e.g., PYTHONOPTIMIZE=1 python worldrepairing_app_repairs_world_shattered_by_worldshattering_app.py).FastMCP users really care about Python optimization. Apparently, nobody else does. Makes sense. Even @beartype is too slow for those speed-obsessed LLM gurus. How can this be!? It's never enough for the AI. In the relentless drive for faster query turnaround times, FastMCP is plumbing the depths of the impossible. There are always casualties on the road to progress. @beartype was one of those casualties. But no more.
@beartype 0.22.5 is a burning phoenix on fire. It's not a metaphor anymore. We're pretty sure our issue tracker is on fire. What is it now? Still 98 open issues despite a flurry of recent issue resolutions that took our last will to code? Yup. 98 open issues. My... my gods. GitHub. Does no one sleep around here? :face_exhaling:
@beartype + PYTHONOPTIMIZE=1: because you're too tired to even run @beartype anymore.
<sup>Speedboat out of nowhere: @beartype. Well-meaning innocent bystanders: FastMCP users.</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:
@strawgate. @Glinte. @bitranox. Heroes among us.
<sup>@beartype and FastMCP. It feels deep.</sup>
@beartype 0.22.4 catastrophically explodes all over your monitor. An oily black residue redolent of snail mucus slides off the screen, dripping with a
@beartype 0.22.4 catastrophically explodes all over your monitor. An oily black residue redolent of snail mucus slides off the screen, dripping with a maddening cadence into the crevices of your trusty mechanical keyboard:
# Via "pip", the once-great venerable master packager now fallen on hard times:
$ pip install --upgrade beartype # <-- you go, pipe-smoking pip
# Via "uv", the plucky upstart spiky-haired kid wielding a sword larger than its body:
$ uv lock --upgrade-package beartype # <-- you do what you need to do, ultraviolet radiation
@beartype 0.22.4 never gets tired of bug-eyed dudes punching squinty-eyed dudes. Childhood memories do not fade.
<sup>Left: @beartype 0.22.4. Right: Poetry and pipenv together as one dude.</sup>
@beartype 0.22.4 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.4 is a patch release that guarantees compatibility with both Poetry and pipenv. Previously, @beartype just assumed that Poetry and pipenv liked @beartype. What's not to like about @beartype, guys? Huh!? Apparently...
Everything. @beartype 0.22.3 broke the assumption that everybody likes @beartype. Our prior release shipped a pyproject.toml file with a PEP 440-compliant version string:
requires-python = ">=3.10,!=3.14rc1,!=3.14rc2"
That syntax is valid. But Poetry and pipenv didn't care. They do what they want! And they didn't want to have anything to do with @beartype 0.22.3. We disagree, but that's fair enough. Everyone has bad opinions.
@beartype 0.22.4 resolves these trivial incompatibilities with popular devtooling. @beartype 0.22.4 also promises this will never happen again. A new integration test in the @beartype test suite guarantees Poetry and pipenv compatibility, safeguarding both your QA stack and sanity against midnight regressions at 4:52AM.
<sup>@beartype 0.22.4: what is even happening here</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:
@nizdolin, @SaiAakash, @markspace, @Spikhalskiy! Because you care, @beartype cares.
<sup>@beartype 0.22.4: it's more painful than it looks, and it looks pretty painful</sup>
One column per quarter.