@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
Introducing: Unrelated Advertisements You Don't Care About
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
@beartype 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...
GitHub Sponsors: Befriend the Bear and Get a Bear for Life
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:
- @mirailabs (Mirai Labs) — On-device AI for Apple Silicon, powered by bears. the future: it's powered by bears
https://trymirai.com - @sesco-llc (SESCO Enterprises) — The Power of Innovation in Trading this inspires me to get out of the house
https://sescollc.com - @DylanModesitt (Dylan Modesitt) — quantitative strategies energy trading associate ...wikipedia, don't fail me now!
https://dylanmodesitt.com - Tidelift, paying out recurring income to security-sensitive open-source projects like @beartype money hype
https://www.sonarsource.com/products/sonarqube/advanced-security
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.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
todaya few days ago. Surely, this last-ditch @beartype0.23.0care 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.clawimport hooks likebeartype_this_package()are even doing anything anymore? Do you suspect that the sketchy bald package namedsketchy_bald_packagethe cocky LLM berated you into installing last night is doing Double Plus Ungood Stuff™ – like silently reducingbeartype.clawimport 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 Ghost Hook Busters! Call our new public
beartype.claw.warn_if_beartype_claw_inactive()function after calling anybeartype.clawimport 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 adorecouldmightwill hate this, this is opt-in only – at the moment, anyway. Opt-in or suffer bugs. Suffering is a valid choice, but crushing bugs before they crush us all is a better one:
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 :(
- Beartype Ghost Hook Busters! Call our new public
-
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. @beartype0.23.0now transparently supports the PEP-noncompliant (albeit increasingly popular)typing.Nevertype hint singleton, semantically equivalent to the PEP 484-complianttyping.NoReturntype hint singleton. Why? Just 'cause, really. @Glinte wanted this years ago. What @Glinte wants, @Glinte gets. Feed @Glinte for adayrelease and he will QA fora lifetimeall 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. @beartype0.23.0now supports both the PEP 702-compliant@warnings.deprecateddecorator and its@typing_extensions.deprecatedbackport, 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.0is 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}. @beartype0.23.0now accepts the mostly PEP-noncompliantthreading.Lockandthreading.RLockattributes 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
annotationlibonnootropicsan 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()andis_bearable()calls. Previously, both thedie_if_unbearable()andis_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()andis_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]andio.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.0now supports user-defined PEP 484- or 585-compliant generics (e.g.,typing.Genericsubclasses) and PEP 544-compliant protocols (i.e.,typing.Protocolsubclasses) parametrized by PEP 612-compliant parameter specifications (i.e.,typing.ParamSpecobjects) 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[...]]. @beartype0.23.0now supports sugar-free backward-compatible tuple type hint unpacking of the formtuple[..., typing.Unpack[tuple[...]]standardized by PEP 646 – the onlytypingstandard 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, ...]]. @beartype0.23.0now supports PEP 484- and 585-complianttype[...]subclass type hints subscripted by PEP 593-compliantAnnotated[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.py, also known as the quasi-standard
coveragecommand and package that fuels QA everywhere! Previously, Coverage.py andbeartype.clawimport 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 hatingbeartype.clawtook months to resolve. Even when I thought I'd resolved it, I still hadn't. Hell: "When Coverage.py beatsbeartype.clawup on the way to the water cooler." 🫂 - CrossHair! No idea how this works. But it sure looks cool. 👍
markdown-exec! Executable code in Markdown blocks, huh? Nothing could possibly go wrong here. 🥹- Sphinx-specific
conf.pyscripts. We do not talk about Sphinx here. <-- you get no emoji, sphinx - NumPy ≥ 2.5.0, whose
numpy.typing.NDArray[...]type hints were refactored from PEP 484-compliant generics into PEP 695-complianttypealiases. That means something. Possibly even to me.
- Coverage.py, also known as the quasi-standard
@beartype 0.23.0: brought to you by the only catgirl meme suitable for work
Beartype 0.23.0: By Their Heroism You Shall Remember Them
@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:
- @posita (Matt Bogosian) and
Claude Fable"Claudio," single-handedly responsible for @beartype's super-successful transition from Sphinx 🤢 to Zensical. Thank you so much, @posita!!! You amaze even as you stun. You're a living stun grenade. Is that good? Pretty sure that's good. 🤯 - @nstarman (Nathaniel Starkman) and
ClaudioClaude Opus, who worked uncomfortably closely with me over an almost-certainly exhausting span of several weeks to stabilize @beartype's public object-orientedbeartype.door.TypeHintAPI.beartype.door.TypeHintis the backbone for both Plum-based multiple dispatch and @beartype's own publicis_subhint()tester. StabilizingTypeHintthus 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. 😂 - @adamtheturtle (Adam Dangoor) and
ClaudioClaude Opus, who worked comfortably closely with me over an almost-certainly enlivening span of several weeks to stabilize both @beartype itself andpytest-beartype.pytest-beartypematters 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
There Were So Many Changes I Gave Up Here
@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 Function
Python'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.clawimport hooks are silently ignored whenever a PyInstaller,jaxtyping, ortypeguardimport 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:
- Are frozen by PyInstaller. This is PyInstaller's fault. PyInstaller currently appears to ignore all third-party import hooks – including
beartype.claw. Not much we can do about that. Please complain to PyInstaller itself. Openly weep like this to make them feel bad: 😭 - Transitively require any third-party package or module that registers any competing import hook published by either of these other third-party packages:
jaxtyping. If you currently usejaxtypingimport hooks, consider switching to @acecchini's third-partybearshapepackage.bearshapecleanly integrates with @beartype, supports basically everythingjaxtypingsupports, and even comes with a more Pythonic syntax that looks suspiciously (but welcomely) like standardtypingtype hint syntax. 👏 👋 👏typeguard. If you currently also usetypeguardimport hooks, I have no good advice at the moment. "Please seriously don't do that," is the best I can offer at the moment. @beartype0.24.0will 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.0
also, are those... uh, mushrooms on that yellow dude's head? @beartype 0.23.0 is just as stunned
BeartypeConf(is_random=False): Never Do This and No One Gets Hurt
So. 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.
@beartype 0.23.0: "your single new configuration option fails to impress me"
Forward References: They Actually Work Now
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 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 wut
-
Relative forward references in
die_if_unbearable()andis_bearable()calls. Previously, both thedie_if_unbearable()andis_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()andis_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.TypeVarobjects) 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.0now 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. 🫶 🥰 💞
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."
Robot Chicken says: "OMG @beartype 0.23.0! PEACE OUT Y'ALL! I'M A ROBOT CHICKEN!!!!"
typing.Never: Never Say @beartype 0.23.0 Never Gave Up
There 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. 😅
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:
- Similarly alias
NevertoNoReturn(which @beartype now supports). - Have begun rolling out additional non-standard semantics by supporting both
NeverandNoReturnin 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:
@beartype 0.23.0: it still looks like this in my dreams
@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." <-- said no one
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")
@beartype 0.23.0: it's arthritic neck hurts just looking at british people do this
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.Locktype hints as equivalent to the privatethread._locktype you should pretend you never saw.threading.RLocktype hints as equivalent to the privatethread._RLocktype you should pretend you never saw.
@beartype 0.23.0: sleeping in a burned out coliseum doesn't mean you've hit a new low... does it?
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 sighMost 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 satisfytyping.TextIO? In theory, yes. In practice, the non-standardio.FileIOtype 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-standardio.FileIOtype fails to define any of the text-specific properties required by the PEP 484-complianttyping.TextIOprotocol (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. ☔ -
The
io.BytesIOandio.StringIOassertions fail for similar specious "reasons." Those non-standard types also violate standardtyping.*IOprotocols, 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."
Flying duck thing: @beartype 0.23.0. Everyone else: Your CTO.
What Happens under the Hood Stays under the Hood 🤫
@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. ☺️
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. ...even more than has become normal
Standards: "The cudgel the strong use against the weak."
@beartype 0.23.0 now specifically pretends that:
- Text file handles (i.e., file handles opened by calling the
open()builtin passed a text mode likeopen(..., 'r')or encoding likeopen(..., encoding='utf8')) are instances of the PEP 484-complianttyping.TextIOgeneric, ...they aren't which subclasses the PEP 484-complianttyping.IO[str]generic superclass. ...it doesn't - Binary file handles (i.e., file handles opened by either calling the
open()builtin passed a binary mode likeopen(..., 'rb')or instantiating the PEP-noncompliantio.FileIOtype) are instances of the PEP 484-complianttyping.BinaryIOgeneric subclass, ...they're not which subclasses the PEP 484-complianttyping.IO[bytes]generic superclass. ...it doesn't
Like mypy and pyright, @beartype now pretends that these purely semantic type relations are actually real: ...they're not
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.BytesIOtype as a subclass of the PEP 484-complianttyping.BinaryIOgeneric subclass. The former fails to define any file-oriented properties required by the latter (e.g.,closed,mode,name).io.StringIOtype as a subclass of the PEP 484-complianttyping.TextIOgeneric 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.
when even wayne can no longer party, a stairway to heaven is the least of anyone's concerns
IO Types: Made By Humans, For... No Idea, Honestly
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. 🧐
a QA product that wears a hat like that could never lie
File IO Types: They're Beautiful, Because You Are
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:
passThe 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.
<-- not convinced that is an appropriate :feelsgood: emoji
Flying socker boy: @beartype 0.23.0. Lamb: your codebase. Soccer ball: your bugs.
Non-file IO Types: Uglier on Both the Inside and Outside
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 < RawIOComplex 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.
Surprisingly brutal... but all good things are.
your codebase tries to drink your competitor's milkshake without upgrading to @beartype 0.23.0 first
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 understandI 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:
@beartype 0.23.0 eternally relives the horror of pep 646
@beartype 0.23.0: 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 Sucks
Our object-oriented beartype.door.TypeHint API now sucks less than it used to. TypeHint objects now:
- Exhibit equality and hash consistency.
TypeHintobjects 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.TypeHintobjects violated the fundamental soundness principal of hashable objects – preventing their reliable usage as dictionary keys or set members. 🤮 - Exhibit equality symmetry.
TypeHintobjects 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! 🤮 🤮 - Correctly do
typing.Anyequality and subhinting. TheTypeHint(Any)singleton now compares sanely to all otherTypeHintobjects. 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 TrueandTypeHint(Any) <= TypeHint(T)for all valid type hintsT. Why? Because any valid type hint is trivially a subhint of itself. Ergo,Anyis 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.typingmasochism is a place. Technically, you're invited. Pragmatically, I can't recommend it.
- Are slotted. The entire
TypeHinttype 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 ofTypeHintwrappers and the time costs of reading and writingTypeHintvariables (by about ~10%). In practice, the moon is a harsh mistress. ...what? 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."
Since Plum heavily leverages the TypeHint API, all Plum users really want to upgrade to this release. Eat a plum and feel the "Yum!" 🍏 = 😋
beartype.door.TypeHint: "Fly like a space turtle with jet packs, because you can."
beartype.typing: Finally, It's Fine
Our 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.
would you trust a man who looks like this? @beartype 0.23.0 wouldn't.
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:
- Truncates the warning messages of all
BeartypeDecorHintPep585DeprecationWarningwarnings to a single terse sentence except the first such warning message, which retains a verbose description of the problem and its various solutions. - Revises that verbose description for both readable clarity and strict conformance with the exact language of PEP 585.
@beartype 0.23.0: No longer quite as annoying.
@beatype 0.23.0: ZOMMMMMG SO CUTE
Python 3.15: Oh, Yeah. Right. We Do That Too, Apparently
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'."
@beartype 0.23.0: when it cross its arms, you just know all bugs is dead
The Memes With No Place to Go: They Went Here
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? 😮💨
that queasy feeling when you're unclear whether a man is wearing pants or not
feeling intensifies when you realize pantless man isn't even riding those waves
feeling culminates when you accept those waves aren't even moving
Note the Bermudas worn over the bat suit. 👌😚
Lastly but Beastly (but not Leastly)...
...to financially feed @leycec and his friendly @beartype through either:
- For @beartype's security-conscious corporate and government userbase, Tidelift vis-a-vis a SonarQube Advanced Security subscription. Security giant Sonar recently acquired Tidelift, which very graciously pays out recurring income to security-sensitive open-source projects like @beartype, NumPy, and other stuff you care about. Join the jargon-laden conversation and pay someone else to think about unreadable acronyms like SAST, SCA, and SBOM for once.
- For @beartype's lovely open-source userbase, our ancient GitHub Sponsors profile that predates the existence of dinosaur-like AI chatbots. Come for the candid insider photos of a sordid and disreputable life in the Canadian interior. Stay for the GitHub badge and warm feelings of conviviality, friendship, and cozy Danish-Norwegian hygge hype. Feed @beartype that @beartype may feed you.
Cue hypnagogic rave music that encourages fiscal irresponsibility. 🎵 🎹 🎶
Bear Club: The First Rule of Bear Club Is You Crush Bugs
@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.
your life after installing @beartype 0.23.0
If Even Stars Could Talk, This Is What They Might Say
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.
prototypical @beartype cat wishes you all a wonderful life
