Tags: patrick-kidger/beartype
Tags
**Beartype 0.15.0** released. @beartype 0.15.0 arises from the ashes of our issue tracker. Now, so too will your codebase. ```bash python3 -m pip install --upgrade beartype ``` Like a cyberpunk phoenix whose intertube veins are made of pure honey and blueberry juice, @beartype 0.15.0 introduces the new `beartype.claw` API. Automate the `@beartype` decorator away with magical import hooks from `beartype.claw`. Do it for the new guy that's sobbing quietly in his cubicle. When you call import hooks published by the `beartype.claw` API, you enable **hybrid runtime-static type-checking.** By "hybrid runtime-static," we mean that `beartype.claw` performs both standard runtime type-checking (ala the `@beartype` decorator) *and* standard static type-checking (ala mypy and `pyright`) **but at runtime** – and that ain't standard. That's right. @beartype is now a tentacular cyberpunk horror like that mutant brain baby from Katsuhiro Otomo's dystopian 80's masterpiece **"Akira."** You can't look away!  <sup>May Neo-Tokyo have mercy on @beartype's soul.</sup> Does this mean that you can now safely discard mypy, `pyright`, and every other pure-static type-checker that your enlightened IDE has unjustly subjected you to over the past several years? In general: * For many of you: "Yes. That is what this means." Pure-static type-checkers lie to you about everything, require maintaining fragile and unreadable `type: ignore[...]` and `pyright: ignore[...]` comment chatter throughout your once-pristine codebase, and fail to enforce anything at test- or runtime. In other words, they (mostly) suck; we should all stop using them, because they (mostly) fail at their core mandate. * For some of you: "No. Please do still use your pure-static 8000 type-checkers." They still excel at use cases that @beartype cannot possibly hope to cover in @leycec's twenty-three next lifetimes as a serial open-source volunteer – including security-oriented use cases like the [PEP 675-compliant `typing.LiteralString` type hint](https://peps.python.org/pep-0675). That's critical. In either case, `beartype.claw` lies less,<sup>...in most cases, much *much* less</sup> requires *no* comment chatter, and enforces everything at test- and runtime. You do still want a real-time IDE linter to catch mundane mistakes like trivial syntactic errors and semantics concerns like obviously undeclared attributes, of course; allow me to now shill for @astral-sh's [magnum opus `ruff`](https://github.com/astral-sh/ruff) here. If it barks, it's either [`ruff`](https://github.com/astral-sh/ruff) or that neighbourhood mongrel harassing our Maine Coons again. Those are domesticated cats, fat doggo – *not* raccoons. Why won't you listen to a human's plea in the night? 😮💨 For those who are about to code, we salute you with all you need to know: ```python from beartype.claw import beartype_this_package # <-- boilerplate for victory beartype_this_package() # <-- congrats. your team just won. ``` **That's it.** That's `beartype.claw` in ten seconds (dyslexia notwithstanding). As the simplest of several import hooks published by the `beartype.claw` API, the `beartype_this_package()` function: * Implicitly decorates *all* callables and classes in `{your_package}` by the `@beartype` decorator. Rejoice, fellow mammals! You no longer need to explicitly decorate anything by `@beartype` ever again. Of course, you still *can* if you want to – but there's no compelling reason to do so and many compelling reasons *not* to do so. You have probably just thought of five, but there are even more. * Implicitly subjects *all* [PEP 526-compliant annotated variable assignments][PEP 526] (e.g., `muh_int: int = 'Pretty sure this isn't an integer.'`) to runtime type-checking via the `beartype.door.die_if_unbearable()` function. More below. Okay, that's *not* it. The `beartype.claw` rabbit hole goes so deep that we couldn't even document anything for this release. Because exhaustion defeated common sense, these release notes are all the documentation.  <sup>This is what happens when we don't `beartype_this_package()`.</sup> `beartype.claw` actually provides **five** vaguely related import hooks. In ascending order of scope, these are... The `beartype.claw.beartyping` context manager is our most self-limiting import hook. When you want to temporarily type-check only a few packages and modules isolated to a single block of code, put that `beartyping` on speed dial: ```python from beartype.claw import beartyping # <-- boilerplate intensifies with beartyping(): # <-- context managers: they manage context import {your_package}.{your_module} # <-- @beartype your own stuff with pride import {their_package}.{their_module} # <-- @beartype somebody else's stuff with or without pride ``` As the above example suggests, all `beartype.claw` import hooks apply equally well to code you and your fearless team have authored, other people's third-party code, and Python's standard library. Whether they intended you to @beartype their stuff or not, do it anyway. Shove @beartype's snuffling snout into every hidden nook and cranny of the Python ecosystem. If it feels good, improves quality assurance, and impresses that weird management guy, could it be wrong?  <sup>The journey of a thousand bugs begins with a single telekinetic leap. `beartype.claw.beartyping`: *this is that leap.*</sup> The `beartype.claw.beartype_this_package()` import hook isolates its bug-hunting action to the **current package.** This is what everyone wants to try first. If `beartype_this_package()` fails, there is little hope for your package. Even though it's probably @beartype's fault, @beartype will still blame you for its mistakes. Typically called as the first statement in your top-level `{your_package}.__init__` submodule, `beartype_this_package()` extends the surprisingly sharp claws of @beartype to *all* callables, classes, and [PEP 526-compliant annotated variable assignments][PEP 526] defined across *all* submodules and subpackages of the current package – regardless of lexical or filesystem nesting depth. As the term "import hook" implies, `beartype_this_package()` only applies to subsequent imports performed *after* that function is called; previously imported submodules and subpackages remain unaffected.  <sup>`beartype_this_package()`: *it do be like that*.</sup> The `beartype.claw.beartype_package()` import hook isolates its bug-hunting action to the **single package or module with the passed absolute name.** Examples or it didn't happen: ```python from beartype.claw import beartype_package # <-- boilerplate continues boilerplating beartype_package('your_package') # <-- they said explicit is better than implicit, # but all i got was this t-shirt and a hicky. ``` Of course, that's fairly worthless. Just call `beartype_this_package()`, right? But what if you wanted to confine `beartype.claw` to a single subpackage or submodule of your package (rather than your *entire* package)? In that case, `beartype_this_package()` is over-*bearing*.<sup>badum ching</sup> Enter `beartype_package()`, the outer limits of QA where you control the horizontal and the vertical: ``` beartype_package('your_package.your_subpackage.your_submodule') # <-- fine-grained precision strike ``` `beartype_package()` shows it true worth, however, in type-checking *other* people's code. Because the `beartype.claw` API is a permissive Sarlacc pit, `beartype_package()` happily accepts the absolute name of *any* package or module – whether they wanted you to do that or not: ```python beartype_package('somebody_elses_package') # <-- blow it up like you just don't care ```  <sup>Truer words were never spoken, wizened psychic baby lady.</sup> The `beartype.claw.beartype_packages()` import hook isolates its bug-hunting action to the **one or more packages or modules with the passed absolute names.** Whereas `beartype_package()` accepts only a single string, `beartype_packages()` accepts an iterable of zero or more strings. One function to QA them all, and in the darkness of our implementation bind them: ```python from beartype.claw import beartype_packages # <-- boilerplate comes to a boil beartype_packages(( 'your_package', 'some_package.published_by.the_rogue_ai.Johnny_Twobits', # <-- seems trustworthy 'numpy', # <-- ...heh. no one knows what will happen here! 'scipy', # <-- ...but we can guess, can't we? *sigh* )) ```  <sup>The end of the road is where `beartype_packages()` is just getting started.</sup> The `beartype.claw.beartype_all()` import hook doesn't isolate anything! It's the ultimate extroverted import hook, spasmodically unleashing a wave of bug-hunting action **across the entire Python ecosystem.** After calling `beartype_all()`, *any* package or module authored by *anybody* (including standard packages and modules in Python's standard library) will be subject to @beartype. This is the extreme QA nuclear option. Because this is the extreme QA nuclear option, **most packages should not do this.** `beartype_all()` forces possibly unwanted `@beartype`-ing on all downstream consumers importing your package. The only packages that should do this are high-level applications run as hegemonic executables (rather than imported by other higher-level applications and packages). @beartype cannot be held responsible for the sudden rupture of normalcy, the space-time continuum, or your previously stable job. For those who are about to explode their codebases, we duck inside a bomb shelter: ```python from beartype.claw import beartype_all # <-- @beartype seemed so innocent, once beartype_all() # <-- where did it all go wrong? ```  <sup>The `beartype_all()` lifestyle is short but sweet, just like @leycec.</sup> This is [PEP 526][PEP 526]: ```python happy_fun_times: str = 0xDEADDEAD # <-- not so happy-fun after all, is it ``` Previously, [PEP 526-compliant annotated variable assignments][PEP 526] were beyond the feeble reach of the Bear. Now, the Bear lovingly fondles those assignments with runtime type-checking fuelled by our `beartype.door.die_if_unbearable()` function. Specifically, for each assignment of the form `var_name: type_hint = new_value` at *any* lexical scope of *any* module imported under an import hook described above, `beartype.claw` appends that assignment by a statement of the form `die_if_unbearable(var_name, type_hint)` type-checking that assignment against that type hint at runtime. `beartype.claw` thus silently expands the above single-line assignment to: e.g., ```python from beartype.door import die_if_unbearable # <-- boilerplate still boilerplating happy_fun_times: str = 0xDEADDEAD # <-- you thought you could hide, bug. but you were wrong die_if_unbearable(happy_fun_times, str) # <-- raise an exception like a dancing necromancer ``` Since the above assignment violates that type hint, `beartype.claw` will now raise a `beartype.roar.BeartypeDoorHintViolation` exception at the point of that assignment. `beartype.claw` ignores all variable assignments that are *not* annotated by type hints: e.g., ```python happy_fun_times = 0xBEEFBEEF # <-- probably not happy-fun, but beartype no longer cares ``` If you hate this, you'll just love our new `BeartypeConf.claw_is_pep526` configuration option. Which leads us directly to...  <sup>Unhappy people forgot to annotate their variable assignments, I see.</sup> We didn't tell you this, because we save the best for last. But *all* of the import hooks described above accept an optional keyword-only `conf: BeartypeConf = BeartypeConf()` parameter (i.e., user-defined beartype configuration, defaulting to the default beartype configuration). Unsurprisingly, that configuration configures all actions performed by the `beartype.claw` API under that import hook: ```python from beartype import BeartypeConf # <-- it all seems so familiar from beartype.claw import beartype_package # <-- boil it up, boilerplate beartype_package('your_package', conf=BeartypeConf(is_pep484_tower=True)) # <-- *UGH.* ``` Equally unsurprisingly, our existing `beartype.BeartypeConf` dataclass has been augmented with new `beartype.claw`-aware super powers. Fine-tune the behaviour of our import hooks for your exact needs, including: * `BeartypeConf(claw_is_pep526: bool = True)`. By default, `beartype.claw` type-checks [PEP 526-compliant annotated variable assignments][PEP 526] like `muh_int: int = 'Pretty sure this isn't an integer.'`. Although this is *usually* what everyone wants, this may not be what someone suspicious dressed in black leather, a red "velvet" cape, and aviator goggles wants in an edge case too unfathomable to even contemplate. If you are such a person, consider disabling this option to reduce runtime safety and destroy your code like Neo-Tokyo vs. Mecha-Baby-Godzilla: <sup>...*who will win!?!?*</sup> ```python from beartype import BeartypeConf # <-- boiling boilerplate... from beartype.claw import beartype_packages # <-- ...boils plates, what? beartype_packages( ('your.subpackage', 'your.submodule'), # <-- pretend this makes sense conf=BeartypeConf(claw_is_pep526=False) # <-- *GAH!* ) ``` * `BeartypeConf(warning_cls_on_decorator_exception: Optional[Type[Warning]] = None)`. By default, `beartype.claw` emits non-fatal warnings rather than fatal exceptions raised by the @beartype decorator at decoration time. This is *usually* what everyone wants, because the @beartype decorator currently fails to support all possible edge cases and is thus likely to raise at least one exception while decorating your entire package. To improve the resilience of `beartype.claw` against those edge cases, @beartype emits one warning for each decoration exception and then simply continues to the next decoratable callable or class. This is occasionally unhelpful. What if you really *do* want `beartype.claw` to raise a fatal exception on the first such edge case in your codebase – perhaps because you either want to see the full exception traceback *or* to punish your coworkers who are violating typing standards by trying to use an imported module as a type hint?<sup>...this actually happened.</sup> In this case, consider passing `None` as the value of this parameter; doing so forces `beartype.claw` to act strictly, inflexibly, and angrily with maximal roaring and blood-flecked claws: ```python from beartype import BeartypeConf # <-- boiling boilerplate... from beartype.claw import beartype_this_package # <-- ...ain't even lukewarm beartype_this_package(conf=BeartypeConf(warning_cls_on_decorator_exception=None)) # <-- *ohboy* ```  <sup>Crack commando Bear-Team: **Assemble!**</sup>  [...to financially feed @leycec and his friendly @beartype through our new GitHub Sponsors profile](https://github.com/sponsors/leycec). Come for the candid insider photos of a sordid and disreputable life in the Canadian interior; stay for the GitHub badge and warm feelings of general goodwill. Cue hypnagogic rave music that encourages fiscal irresponsibility. 🎵 🎹 🎶 Greets to: * [Python-on-whales (i.e., Pythonic Docker API)](https://github.com/gabrieldemarmiesse/python-on-whales) mastermind @gabrieldemarmiesse (Gabriel de Marmiesse) for their tireless dedication to the just cause of `beartype.claw`. @gabrieldemarmiesse went above the call of the wild, relentlessly previewing live unstable commits to the `beartype.claw` API against both open-source *and* proprietary projects. Two paws in the air, 'cause you know Gabriel care! 🐾 * @qutebrowser maestro @The-Compiler (Florian Bruhin) for repeatedly weighing in with bad `beartype.claw` breakage against real-world use cases – including @qutebrowser itself. This is the stuff dream teams are made of. High fives for the glory of Python. ✋ ✋ * The *berry* great bear bros @wesselb and @posita for their unwavering awesomeness. [Plum](https://github.com/beartype/plum) is that zesty fruit which satisfies all your multiple dispatch needs you didn't know you had... *but you had.* * The tireless bear cubs on our issue tracker, who make @beartype better by pointing out how ~~awful~~ less than ideal it still is: @jklaise, @skeggse, @yurivict, @rsokl, @KyleKing, @kloczek, @justinchuby, @alexander-c-b, @machow, @JWCS, @Skylion007, @eohomegrownapps, @BowenBao, @k4ml, @tolomea, and @zeevox. And... I'm spent. Clearly, this mega-issue is also spent. Fifteen million meme images and dissertation-length monologuing have clogged the Intertubes beyond repair. With an appreciable sigh of relief as we move into the new age of `beartype.claw`, let's close this venerable thread. All newer release announcements will be posted to [our peanut gallery](https://github.com/beartype/beartype/discussions). Goodbye, **Future Sound of Beartype.** Thanks for all the salmon. [PEP 526]: https://peps.python.org/pep-0526  <sup>`beartype.claw` rises with the paw of quality. Will you high-five that paw?</sup>
**Beartype 0.14.1** released. This patch release delivers enthusiastic ~~hijinx~~ quality assurance with improved support for [third-party `typing_extensions` backports](https://pypi.org/project/typing-extensions), [PEP 517][PEP 517] (i.e., `pyproject.toml`), [PEP 544][PEP 544] (i.e., `typing.Protocol`), and [PEP 585][PEP 585] (i.e., `re.Match` and `re.Pattern`). Codebases everywhere can now release a grateful sigh of relief as bugs buckle under the combined might of @beartype **+** `typing_extensions`. Flex the muscles you knew you always had. This patch release resolves **3 issues.** Wave those paws in the air like your project manager just don't care! * **[PEP 517][PEP 517].** This release restores our [PEP 517][PEP 517]-compliant top-level `pyproject.toml` file in a vain and probably misguided attempt to restore the buildability of our documentation on the third-party ReadTheDocs (RTD) documentation host. Doing so nudges @beartype mildly closer towards abandoning the antiquated (and frankly objectionable) `setuptools` build system to Hatch, officially endorsed by the Python Packaging Authority (PyPA) as sane and *not* `setuptools`, which are the only criteria @leycec is looking for in a Python build system. The bar could *not* be lower. * **[PEP 544][PEP 544].** @beartype now officially supports *all* third-party `typing_extensions.Protocol` backports, resolving issue beartype#241 kindly submitted by MIT machine learning guru @rsokl (Ryan Soklaski). This release also restores testing of the `typing_extensions.Protocol` superclass, which now passes under *all* `typing_extensions` versions. Let's not ask prying and uncomfortable questions about what exactly was resolved here, because then @leycec might break down and openly weep emoji tears live on GitHub. * **[PEP 585][PEP 585].** This release "undeprecates" the `beartype.typing.{Match,Pattern}` type hints deprecated by [PEP 585][PEP 585], resolving issue beartype#240 kindly submitted by AI King @KyleKing (Kyle King). Specifically, the `beartype.typing` subpackage now imports those type hints from the standard `re` rather than `typing` module under Python >= 3.9. This is why @leycec sighs in his sleep while clutching a Bengal plushy. * **[PEP 673][PEP 673] FAQ entry.** This release documents why [PEP 673][PEP 673] (i.e., `typing.Self`) officially supported by @beartype ≥ 0.14.0 is the substantially superior choice to either [PEP 484][PEP 484]-compliant forward references or [PEP 563][PEP 563]-compliant postponed type hints for type-checking a class self-referentially. Specifically, this release adds a [new "...the current class?" question to our existing FAQ](https://beartype.readthedocs.io/en/latest/faq/#the-current-class). In theory, this *should* clear up the smelly mountain of confusion surrounding this topic both on and off our issue tracker. * **Project URL generalization.** This release generalizes project URLs in our Sphinx configuration from the Sphinx-specific `doc/src/conf.py` script to the Sphinx-agnostic `beartype.meta` submodule, enabling generic reuse of those URLs across numerous third-party frameworks rather than merely Sphinx. In short, nothing worthwhile was done. [PEP 484]: https://peps.python.org/pep-0484 [PEP 517]: https://peps.python.org/pep-0517 [PEP 544]: https://peps.python.org/pep-0544 [PEP 563]: https://peps.python.org/pep-0563 [PEP 585]: https://peps.python.org/pep-0585 [PEP 621]: https://peps.python.org/pep-0621 [PEP 673]: https://peps.python.org/pep-0673 (*Lush brush, last blast, and crass lass combine rash lashes!*)
**Beartype 0.14.0** released. This minor release brings exhilerating support for **[PEP 673][PEP 673]** (`typing.Self`) and **[PEP 675][PEP 675]** (`typing.LiteralString`) as well as substantially improved compatibility with PyPy. This minor release resolves **2 issues.** But first, a brief word from our tenebrous sponsors. They are gentlemanly alchemists who dispense truth and money while despoiling bugs in your codebase. All thumbs up, please! * [**ZeroGuard:** The Modern Threat Hunting Platform](https://zeroguard.com). *All the signals, All the time.* A chorus of overwhelming jubilation chimes through the stuffy confines of the Bear Den. 👏 🐻❄️ 👏 And now... the time we've waited for. A ribald display of plaintext that manhandles all twelve major meridian lines concurrently. * **[PEP 673][PEP 673].** @beartype now deeply type-checks **[PEP 673 – Self Type][PEP 673]** (i.e., `typing.Self`). @beartype now fully supports `typing.Self` type hints in @beartype-decorated classes. Specifically: * For each `typing.Self` type hint annotating something *inside* the body of a class (e.g., method parameter or return, class variable), @beartype now reduces that hint to that class. * For each `typing.Self` type hint annotating something *outside* the body of a class (e.g., function parameter or return, global variable), @beartype now raises an exception gently advising you to rethink life choices. * **[PEP 675][PEP 675].** @beartype now shallowly type-checks **[PEP 675 – Arbitrary Literal String Type][PEP 675]** (i.e., `typing.LiteralString`). As [PEP 675][PEP 675] advises for runtime type-checkers, @beartype now reduces (i.e., aliases) all `typing.LiteralString` type hints to the standard `str` type. Sadly, deeply type-checking literal strings is intractable for runtime type-checkers and is the textbook example of validation that can be performed *only* by static type-checkers. Type-checking literal strings requires: * Efficiently parsing abstract syntax trees (ASTs) at runtime (which is technically feasible, given sufficiently aggressive caching). * Correctly transitively inferring literal strings across operations and calls (which requires parsing the entire codebase of the app stack and constructing an in-memory graph of all type relations, which is pragmatically This isn't to say that [PEP 675][PEP 675] is bad, however. [PEP 675][PEP 675] is actually *incredible*, reducing the attack surface of database injection attacks at static analysis time with *no* harmful tradeoffs. And... who knows? With enough intestinal fortitude, handlebar mustaches, and monocled eyepieces, perhaps even @beartype can surmount this Hill of Thorns. * **PyPy**. This release resolves a significant incompatibility with PyPy, whose implementation of the `id()` builtin appears to occasionally (read: non-deterministically) return object identifiers that are negative integers. Specifically, @beartype now guaranteeably generates valid parameter names passed to type-checking wrapper functions regardless of the sign of the `id()` of the values of those parameters. Doing so resolves issue beartype#232 kindly submitted by @jvesely (Jan Vesely) who purportedly lives in or around an ancient pork by-product that has calcified into stone -- which is quite impressive, really. Stoneham: it's like Stonehenge, only American and yummy in your tummy. Thanks so much for the heads up, @jvesely. * **Readable violation messages.** This release improves the readability of type-checking violation messages raised by @beartype, en-route to resolving feature request beartype#216 kindly submitted by @felixchenier (AKA, *le maître québécois en assurance qualité*). Specifically, @beartype now prefixes type-checking violation messages with a terse description of the responsible callable (e.g., `"Function"`, `"Coroutine factory method"`) rather than the meaningless prefix `"@beartyped"`. Explicitly detected types of callables include: * Coroutine factory functions, instance methods, and class methods. * Asynchronous generator factory functions, instance methods, and class methods. * Synchronous generator factory functions, instance methods, and class methods. * "Normal" synchronous functions, instance methods, and class methods. * **Module detection.** This release commit dramatically simplifies the private `beartype._util.mod.utilmodtest.is_module_version_at_least()` tester to cease deferring to the fragile third-party `pkg_resources` package -- which now emits `DeprecationWarning` warnings implicitly coerced by pytest into test failures. Begone, foul `pkg_resources`! * **Added:** * A new public [PEP 673][PEP 673]-specific `beartype.roar.BeartypeDecorHintPep673Exception` exception subclass. [PEP 673]: https://peps.python.org/pep-0673 [PEP 675]: https://peps.python.org/pep-0675 (*Plucky puppies in a saggy rucksack!*)
**Beartype 0.13.1** released. This patch release brings titillating support for **working tests.** That's right; the prior minor release broke tests by failing to ship the `mypy.ini` configuration file in tarballed sdists, thereby breaking the `test_pep561_mypy()` integration test when run from tarballed sdists. This is why we facepalm. This patch release resolves **1 issue** and merges **1 pull request.** But first, a quiet word from our wondrous sponsors. They are monocled QA wizards who serve justice while crushing bugs for humanity. High fives, please! * [**ZeroGuard:** The Modern Threat Hunting Platform](https://zeroguard.com). *All the signals, All the time.* Thunderous applause echoes through the cavernous confines of the Bear Den. 👏 🐻❄️ 👏 And now... the moment we've waited for. A heinous display of plaintext that assaults all five senses simultaneously. * The `test_pep561_mypy()` integration test validating that @beartype passes all mypy-specific static runtime type-checks, thanks to a pull request from @mgorny the Gentoo Guy Who Knows All and Codes All. (*Vapid vapor pours rapidly!*)
**Beartype 0.13.0** released. This minor release delivers pulse-quickening support for **pandera (pandas) type hints,** **PEP 484,** **PEP 585**, **PEP 591**, **PEP 647**, **PEP 3119**, and **pseudo-callables.** This minor release resolves **12 issues** and merges **2 pull requests.** But first, a quiet word from our wondrous sponsors. They are monocled QA wizards who serve justice while crushing bugs for humanity. High fives, please! * [**ZeroGuard:** The Modern Threat Hunting Platform](https://zeroguard.com). *All the signals, All the time.* Thunderous applause echoes through the cavernous confines of the Bear Den. 👏 🐻❄️ 👏 And now... the moment we've waited for. A heinous display of plaintext that assaults all five senses simultaneously. * **Pandera (pandas) type hints** (i.e., ad-hoc PEP-noncompliant type hints validating pandas `DataFrame` objects, produced by subscripting factories published by the `pandera.typing` subpackage and validated *only* by user-defined callables decorated by the ad-hoc PEP-noncompliant `@pandera.check_types` runtime type-checking decorator), resolving feature request beartype#227 kindly submitted by @ulfaslakprecis (Ulf Aslak) the Big Boss Typer. @beartype now: * Transparently supports pandera's PEP-noncompliant `@pandera.check_types` decorator for deeply runtime type-checking arbitrary pandas objects. * *Always* performs a rudimentary `O(1)` `isinstance()`-based type-check for each Pandera type hint. Doing so substantially improves usability in common use cases, including: * Callables annotated by one or more pandera type hints that are correctly decorated by @beartype but incorrectly *not* decorated by the pandera-specific `@pandera.check_types` decorator. * (Data)classes annotated by one or more pandera type hints. * Pandera type hints passed as the second argument to statement-level @beartype type-checkers – including: * `beartype.door.is_bearable()`. * `beartype.door.die_if_unbearable()`. * Implements a non-trivial trie data structure to efficiently detect all type hints produced by subscriptable factories in the `pandera.typing` submodule. Let us pretend this never happened, @ulfaslakprecis. * **PEP 484- and 585-compliant generator constraints.** This release relaxes prior constraints erroneously imposed by @beartype prohibiting both asynchronous and synchronous generator callables from being annotated as returning unsubscripted standard abstract base classes (ABCs) defined by the `collections.abc` module. Now, @beartype permits: * Asynchronous generator callables to be annotated as returning the unsubscripted `collections.abc.AsyncGenerator` type. * Synchronous generator callables to be annotated as returning the unsubscripted `collections.abc.Generator` type. * **PEP 591** (i.e., `typing.Final[...]` type hints), partially resolving issue beartype#223 kindly submitted by the acronym known only as @JWCS (Jude). @beartype now trivially reduces *all* `typing.Final[{hint}]` type hints to merely `{hint}` (e.g., `typing.Final[int]` to `int`). In other words, @beartype no longer raises exceptions when confronted with final type hints and instead at least tries to do the right thing. This still isn't *quite* what everyone wants @beartype to do here; ideally, @beartype should also raise exceptions on detecting attempts to redefine instance and class variables annotated as `Final[...]`. Doing so is *definitely* feasible and exactly what @beartype should *eventually* do – but also non-trivial, because whatever @beartype *eventually* does needs to preserve compatibility with all implementations of the `@dataclass` decorator across all versions of Python now and forever. Cue that head-throbbing migraine. It's comin'! Oh, I can feel it! * **PEP 647** (i.e., `typing.TypeGuard[...] type hints`), resolving feature request beartype#221 kindly submitted by Google X researcher extraordinaire @patrick-kidger. @beartype now trivially reduces *all* `typing.TypeGuard[...]` type hints to the builtin `bool` type. * **PEP 3119.** @beartype now detects both **non-isinstanceable classes** (i.e., classes whose metaclasses define PEP 3119-compliant `__instancecheck__()` dunder methods unconditionally raising `TypeError` exceptions) and **non-issubclassable classes** (i.e., classes whose metaclasses define PEP 3119-compliant `__subclasscheck__()` dunder methods unconditionally raising `TypeError` exceptions) more narrowly for safety, resolving issue beartype#220 kindly submitted by *ex*traordinary Google X researcher @patrick-kidger (Patrick Kidger). Notably, @beartype now *only* accepts `TypeError` exceptions as connoting non-isinstanceability and non-issubclassability. Previously, @beartype broadly treated any class raising any exception whatsoever when passed as the second parameter to `isinstance()` and `issubclass()` as non-isinstanceable and non-issubclassable. Sadly, doing so erroneously raises false positives for isinstanceable and issubclassable metaclasses that have yet to be fully "initialized" at the early time the `@beartype` decorator performs this detection. * **Pseudo-callable monkey-patching support.** `@beartype` now supports **pseudo-callables** (i.e., otherwise uncallable objects masquerading as callable by defining the `__call__()` dunder method), resolving feature request beartype#211 kindly submitted by Google X typing guru @patrick-kidger (Patrick Kidger). When passed a pseudo-callable whose `__call__()` method is annotated by one or more type hints, `@beartype` runtime type-checks that method in the standard way. * **Literally everything,** also known as the release that migrated `README.rst` -> [Read the Docs (RtD)](https://beartype.readthedocs.io), resolving both issue beartype#203 kindly submitted by @LittleBigGene (AKA the dynamo of the cell) and ancient issue beartype#8 kindly submitted by @felix-hilden (AKA the Finnish computer vision art genius that really made all of this possible). Readable documentation slowly emerges from the primordial soup of @beartype's shameless past for which we cannot be blamed. @leycec was young and "spirited" back then. Specifically, this release: * Coerces our prior monolithic slab of unreadable `README.rst` documentation into a website graciously hosted by Read the Docs (RtD) subdividing that prior documentation into well-structured pages, resolving issue beartype#203 kindly submitted by @LittleBigGene (AKA the dynamo of the cell). * Documents *most* previously undocumented public APIs in the @beartype codebase. Although a handful of public APIs remain undocumented (notably, the `beartype.peps` submodule), these undocumented APIs are assumed to either be sufficiently unpopular or non-useful to warrant investing additional scarce resources here. * Updates our installation instructions to note @beartype's recent availability as official packages in the official package repositories of various Linux distributions. Truly, this can only be the final mark of pride. These include: * Gentoo Linux's Portage tree. * Arch Linux's Arch User Repository (AUR). * Improves the Python code sample embedded in the ["Are We on the Worst Timeline?" subsection of our **Beartype Errors** chapter](https://beartype.readthedocs.io/en/latest/api_roar/#are-we-on-the-worst-timeline). Thanks to @JWCS for their related pull request (PR) beartype#210, which strongly inspired this bald-faced improvement to the usability of our `beartype.typing` API. * Circumvents multiple long-standing upstream issues in the PyData Sphinx theme regarding empty left sidebars via the requisite `_templates/sidebar-nav-bs.html` template hack shamelessly copy-pasted into literally *every* project requiring this theme. This includes @beartype, because why not spew boilerplate that nobody understands everywhere? Sadly, doing so requires pinning to a maximum obsolete version of this theme that will surely die soon. And this is why I facepalm. These issues include: * pydata/pydata-sphinx-theme#90. * pydata/pydata-sphinx-theme#221. * pydata/pydata-sphinx-theme#1181. * Truncates our `README.rst` documentation to a placeholder stub that just directs everyone to RtD instead. * Improves `linecache` integration commentary. Specifically, a pull request by @faangbait (AKA the little-known third member of Daft Punk) improves internal commentary in our private `beartype._util.func.utilfuncmake.make_func()` factory function responsible for dynamically synthesizing new in-memory functions on-the-fly. Our suspicious usage of `None` as the second item of tuples added as values to the standard `linecache.cache` global dictionary has now been documented. Thanks so much for this stupendous contribution, @faangbait! * **Mypy integration.** This release improves our `test_pep561_mypy()` integration test to intentionally ignore unhelpful non-fatal warnings improperly emitted by mypy (which encourage usage of `typing_extensions`, oddly enough). * **Sphinx integration.** This release resolves multiple intersecting issues involving integration testing of Sphinx + @beartype, including: * `test_beartype_in_sphinx()` h0tfix is h0t. This release generalizes our test-specific `test_beartype_in_sphinx()` integration test to support arbitrary versions of Sphinx, resolving issue beartype#209 kindly submitted by @danigm the sun-loving Málaga resident who frolics in the sea that Canadians everywhere are openly jealous of. Specifically, this release fundamentally refactors this integration test to fork a new Python interpreter as a subprocess of the current `pytest` process running the `sphinx-build` command. * A Python 3.7-specific failure in our continuous integration (CI) workflow caused by Sphinx attempting to call deprecated functionality of the third-party `pkg_resources` package. This release simply avoids installing Sphinx entirely under Python 3.7; although admittedly crude, it's unclear how else @beartype could possibly resolve this. Since Python 3.7 has almost hit its official End-Of-Life (EOL) and thus increasingly poses a security concern, this is hardly the worst resolution ever. Really! Believe what we're saying. Break nothing! It's the @beartype way. This is why @leycec cries like a mewling cat with no milk. (*Thrilling chills spill towards an untoward ontology!*)
**Beartype 0.12.0** released. This minor release expands the infinitely vast (yet mostly empty) universe of @beartype into the hitherto uncharted realms of **configuration,** **exception identification,** **Nuitka,** **`typing.NamedTuple`,** and **Python 3.11.** Also, other things were done. We swear it! This minor release resolves **16 issues** and merges **2 pull requests.** Noteworthy changes include: * **Python 3.11.** This is the first @beartype support to officially support the recently released Python 3.11. Notably, this release: * Synchronizes our public `beartype.typing` subpackage against upstream changes in the standard `typing` module introduced in Python 3.11. * Supports PEP-compliant type hints subscripted by the empty tuple (e.g., `typing.Tuple[()]`), whose low-level implemen 8000 tation fundamentally changed under Python 3.11. * Updates our GitHub Actions-based continuous integration (CI) workflow to exercise @beartype against Python 3.11. * **Nuitka.** This is the first @beartype release to officially support Nuitka (i.e., the increasingly popular Python compiler that stuns us all), resolving feature request beartype#197 kindly submitted by @shenwpo (also known as the giant flaming metallic letter e). This includes a new `test_nuitka()` integration test showing that Nuitka successfully compiles a minimal-length example (MLE) runtime type-checked by @beartype. * **`typing.NamedTuple`.** This release adds support for deeply type-checking subclasses of the PEP 484-compliant `typing.NamedTuple` superclass. Specifically, this release improves the resiliency of our PEP 563 resolution mechanism (i.e., the public `beartype.peps.resolve_pep563()` function) against callables whose `__module__` dunder attributes lie. This includes *all* `typing.NamedTuple` subclasses, which synthesize callables whose `__module__` dunder attributes erroneously claim to reside in the non-existent `"namedtuple_Foo"` module. Doing so resolves issue beartype#181 kindly submitted by probably ingenious "Probabilistic Machine Learning" author @murphyk (Kevin P. Murphy). * **Beartype configuration API.** This release publishes a new public API for externally configuring @beartype via the now-official `beartype.BeartypeConf` type and `beartype.BeartypeStrategy` enumeration. Specifically, this release adds: * **`beartype.BeartypeConf.is_color`,** a new tri-state boolean enabling end users to control how and whether beartype colours **type-checking violations** (i.e., :class:`beartype.roar.BeartypeCallHintViolation` exceptions) with POSIX-compliant ANSI escape sequences for readability, resolving issue beartype#178 kindly submitted by the foxy ZeroGuard and River Oakfield founder @foxx (Cal Leeming). Rejoice, typing acolytes, for you have now been freed from the prismatic shackles of the rainbow! * **`beartype.BeartypeConf.is_pep484_tower`**, a new standard boolean enabling end users to control whether @beartype supports the [implicit numeric tower standardized by PEP 484](https://peps.python.org/pep-0484/#the-numeric-tower) or not, resolving issue beartype#174 kindly submitted by dashing French Canadian @felixchenier (Félix Chénier). * **`beartype.BeartypeStrategy.O0`**, a new **no-time strategy** (i.e., beartype configuration option generalizing the standard `@typing.no_type_check` decorator). Enabling this strategy instructs the `@beartype` decorator to recall and preserve previously applied no-time strategies; internally, `@beartype` detects and reduces configurations resembling `conf=BeartypeConf(strategy=BeartypeStrategy.O0, ...)` to the `@typing.no_type_check` decorator. Users may now blacklist specific callables from being type-checked by configuring this strategy as documented in our front-facing `README.rst` documentation... *somewhere.* It's in there somewhere, people. * **Beartype exception API.** This release publishes a new public API for externally identifying the cause of **type-checking violations** (i.e., instances of the `beartype.roar.BeartypeCallHintViolation` exception class) raised by @beartype. These exceptions now publicly expose the user-defined objects responsible for those violations via a new `BeartypeCallHintViolation.culprits` property, resolving feature request beartype#180 kindly submitted by @Jasha10 the Supremely Patient and Understanding GitHubber. For safety, this property dynamically returns a non-empty tuple of the one or more responsible culprits defined as either: * For each culprit that supports weak references and is still alive (i.e., has yet to be garbage-collected), that culprit as is. * Else, the machine-readable string representation of that culprit truncated to a reasonable number of characters. * **`beartype.roar.BeartypeAbby*Exception`.** This release deprecates all lingering remnants of the prior `beartype.abby` subpackage – including: * `beartype.roar.BeartypeAbbyException`, supplanted by `beartype.roar.BeartypeDoorException`. * `beartype.roar.BeartypeAbbyHintViolation`, supplanted by `beartype.roar.BeartypeDoorHintViolation`. * `beartype.roar.BeartypeAbbyTesterException`, supplanted by `beartype.roar.BeartypeDoorException`. * **@beartype exports.** This release terminally pacifies: * Mypy by publicizing all exported attributes from the top-level `beartype` package via a new `beartype.__all__` dunder attribute. Thanks to the stylishly pink-haired @pinkwah (Zohar Malamant) for the rapid pull request (PR). * `pyright` by explicitly re-exporting all public attributes of the top-level `beartype` package, resolving issue beartype#169 kindly submitted by MIT AI mastermind @rsokl (Ryan Soklaski). * **Continuous integration (CI).** This release integrates our GitHub Actions-based continuous integration (CI) workflow (i.e., `.github/workflows/python_test.yml`) with third-party GitHub Actions statically type-checking beartype against both `mypy` and `pyright` at CI time – including on every commit as well as pull request (PR). For both robustness and efficiency, this release prevents functional tests in our test suite that perform these same static type-checks from running under CI. Doing so resolves a furious spate of spurious CI complaints. So what we did there? We rhymed. Notably, this release: * Leverages @jakebailey's superb `jakebailey/pyright-action` action to exercise @beartype against `pyright` at CI time. * Manually installs and runs `mypy` in a low-level manner under CI *without* leveraging @jpetrucciani's otherwise stellar `jpetrucciani/mypy-check` action -- which @beartype hopes to revisit at a later date when the issue tracker settles there a bit. Thanks so much, @jpetrucciani! You dah real QA MVP. * **`beartype.door.TypeHint` comparisons.** This release significantly improves the robustness of comparison operators overloaded by the object-oriented `beartype.door.TypeHint` API, resolving issue beartype#198 kindly submitted by @wesselb the phenomenal Amsterdammer of [Plum](https://github.com/wesselb/plum) fame. This includes edge cases when: * Comparing unions against both other unions *and* non-unions (e.g., `typing.Any`, isinstanceable classes). * Comparing tuple type hints against `typing.Any`. * **`beartype.BeartypeConf` caching.** This release resolves a critical (yet ultimately trivial) caching issue with respect to `beartype.BeartypeConf` singletons, in which singletons initialized with different parameters could conceivably have been erroneously cached to the same object. Hash collisions! I see hash collisions everywhere! * **Call stack iteration robustness.** This release resolves an edge case in our private `beartype._util.func.utilfuncframe.iter_frames()` generator iterating over stack frames on the current call stack. Specifically, this generator now safely reduces to the empty generator (i.e., noop) when the caller requested that generator ignore more stack frames than exist on the call stack. Although raising an exception would also be feasible, doing so would only needlessly increase the fragility of this already fragile mission-critical generator. * **Broken anchor links.** This release repairs broken anchor links dotted throughout our monolithic `README.rst` to actually point to valid (sub)sections. * **Sphinx configuration.** This release reconfigures the lackluster coffin that is our Sphinx configuration, en-route to resolving issue beartype#8 (!) kindly submitted a literal lifetime ago by visionary computer vision export and long-standing phenomenal Finn @felix-hilden (Felix Hildén). Specifically, this release: * **Enables Furo,** switching from the default Read The Docs (RTD) Sphinx theme to the third-party Furo theme. We selected this theme according to mostly objective (albeit ultimately subjective) heuristic criteria. In descending order of importance, we selected the theme with: 1. The most frequent git commit history. 2. The open issues and pull requests (PRs). 3. The most GitHub stars as a crude proxy for aggregate rating. Furo handily bested all other themes across all three criteria. Furo is very well-maintained, frequently closes out open issues and merges open PRs, and sports the highest quantity of GitHub stars by an overwhelming margin. `\o/` * **Enables the builtin `intersphinx` extension,** enabling attributes defined by the standard library (e.g., the `typing` module, the `types.GenericAlias` type) to be cross-referenced as a fallback when *not* already defined by this project. * **Reconfigures RTD** through our top-level `.readthedocs.yml` configuration to: * Build under the most recent Long Term Service (LTS) release of Ubuntu. * Build under the most recently released minor version of CPython. * Configure Sphinx via our `doc/source/conf.py` script. * **Restores the standard `sys.path` hack** – which, for unknown reasons, @leycec disabled but thankfully left commented out. Doing so re-resolves issue beartype#120, kindly submitted by @kloczek (Tomasz Kłoczko) five friggin' months ago. Thanks so much for the fast patch and rapid turn-around, @kloczek! * **Improves pathname robustness** by intelligently detecting documentation paths via the standard `pathlib.Path` API. * **Enables `autoapi`.** This release successfully transitions from Sphinx's builtin (but insane) `autodoc` and `autosummary` extensions to Read The Doc (RTD)'s non-builtin (but sane) `autoapi` extension. * **Adds a local URI store** (i.e., hidden reStructuredText (reST) document centralizing common URI links in reST format, automatically exposed to all other reST documents in this project via the `rst_epilog` setting in `conf.py`) at `doc/src/_links.rst`. * **Removes obsolete cruft,** which accrues with time like entropic motes in God's eye. That was a reference to a Golden Age of Scifi book, people! Don't ask why God only has one eye. It's better not to contemplate these matters. * **Ruthlessly circumvents upstream issue sphinx-doc/sphinx#4961,** causing Sphinx to emit literally hundreds of ignorable warnings resembling ``"WARNING: more than one target found for cross-reference 'TypeHint':`` ``beartype.door._doorcls.TypeHint, beartype.door.TypeHint"`` with a [trivial circumvention shamelessly pilfered from @RDFLib](https://github.com/RDFLib/rdflib/blob/3a418218d6bcdb46f78342e14c024063e2f53e71/docs/conf.py#L255). * **[Beartype Object-oriented API](https://github.com/beartype/beartype/tree/76aebd63b5f32ac6bdab6420eb0c9bfa2ca09b29#id36).** This release prefaces our "Beartype Object-oriented API" subsection with a human-readable discussion of the Decidedly Object-Oriented Runtime-checking (DOOR) – also known as "That API Which Breaks Hearts and Minds Alike." * **[Procedural Showcase]**(https://github.com/beartype/beartype/#procedural-showcase). This release adds a new *Procedural Showcase* subsection containing a new *Detect API Breakage* subsubsection exhibiting a real-world usage for our recently published `beartype.door.is_subhint()` tester: detecting API breakage across the type hints annotating arbitrary callables in exactly ten lines of code. * **[Near-real-time FAQ entry](https://github.com/beartype/beartype/#beartype-realtime).** This release adds a new FAQ entry entitled *What does "near-real-time" even mean?*, justifying our recent categorization of @beartype as a "near-real-time runtime type-checker." Let's pretend @leycec knows what he's talking about. * **[JAX, Numpy, and PyTorch FAQ entries](https://github.com/beartype/beartype/#jax-arrays).** This release expands our existing FAQ with entries on typing JAX and NumPy arrays and PyTorch tensors to highlight the stupefying potential unlocked by the third-party `jaxtyping`, `nptyping`, and TorchTyping packages, resolving issue beartype#98 submitted a literal lifetime ago by Edinburgh NLP researcher @amitkparekh (Amit Parekh). * **[VSCode FAQ entry](https://github.com/beartype/beartype/tree/76aebd63b5f32ac6bdab6420eb0c9bfa2ca09b29#id28).** This release rewrites our entire FAQ entry on `pyright` + Pylance + VSCode to be significantly more charitable towards `pyright`, resolving issue beartype#170 kindly submitted by MIT AI mastermind @rsokl (Ryan Soklaski). * **[Type narrowing FAQ entry](https://github.com/beartype/beartype/tree/76aebd63b5f32ac6bdab6420eb0c9bfa2ca09b29#id30).** This release adds a new FAQ entry on type narrowing, strongly inspired by (*...wait for it*) MIT AI mastermind @rsokl (Ryan Soklaski)'s equally masterful writing at issue beartype#166. (*Powerful bowers full of flowers!*)
**Beartype 0.11.0** released. This minor release unleashes a major firestorm of support for **class decoration,** **colourful exceptions,** **pyright + PyLance + VSCode,** the **D**ecidedly **O**bject-**O**rientedly **R**ecursive (DOOR) API, the **P**ython **E**nhancement **P**roposal**s** (PEPs) API, [PEP 484][PEP 484], [PEP 544][PEP 544], [PEP 561][PEP 561], [PEP 563][PEP 563], [PEP 585][PEP 585], [PEP 604][PEP 604], [PEP 612][PEP 612], and [PEP 647][PEP 647]. This minor release resolves a mammoth **29 issues** and merges **12 pull requests.** Noteworthy changes include: * **Class decoration.** The `@beartype` decorator now decorates both higher-level classes *and* lower-level callables (i.e., functions, methods), resolving feature request beartype#152 kindly submitted by @posita the positively sublime. All possible edge cases are supported, including: * Classes defining methods decorated by builtin decorators: i.e., * Class methods via `@classmethod`. * Static methods via `@staticmethod`. * Property getters, setters, and deleters via `@property`. * Arbitrarily deeply nested (i.e., inner) classes. * Arbitrarily deeply nested (i.e., inner) classes whose type hints are postponed under [PEP 563][PEP 563]. Since this was surprisingly trivial, @leycec p 8000 robably should have done this a few years ago. He didn't. This is why he laments into his oatmeal in late 2022. * **[PEP 484][PEP 484]- and [PEP 585][PEP 585]-compliant nested generics.** @beartype now supports arbitrarily complex [PEP 484][PEP 484]- and [PEP 585][PEP 585]-compliant inheritance trees subclassing non-trivial combinations of the `typing.Generic` superclass and other `typing` pseudo-superclasses, resolving issue beartype#140 kindly submitted by @langfield (William Blake – yes, *that* William Blake). Notably, this release extricated our transitive visitation of the tree of all pseudo-superclasses of any PEP 484- and 585-compliant generic type hint (*...don't ask*) from its prior hidden sacred cave deep within the private `beartype._decor._code._pep._pephint` submodule into a new reusable `iter_hint_pep484585_generic_bases_unerased_tree()` generator, which is now believed to be the most fully-compliant algorithm for traversing generic inheritance trees at runtime. This cleanly resolved all lingering issues surrounding generics, dramatically reduced the likelihood of more issues surrounding generics, and streamlined the resolution of any more issues surrounding generics should they arise... *which they won't.* Generics: we have resoundingly beaten you. Stay down, please. * **[PEP 544][PEP 544] compatibility.** @beartype now supports arbitrarily complex [PEP 544][PEP 544]-compliant inheritance trees subclassing non-trivial combinations of the `typing.Protocol` + `abc.ABC` superclasses, resolving beartype#117 kindly submitted by too-entertaining pun master @twoertwein (Torsten Wörtwein). Notably, `@beartype` now: * Correctly detects non-protocols as non-protocols. Previously, @beartype erroneously detected a subset of non-protocols as PEP 544-compliant protocols. It's best not to ask why. * Ignores both the unsubscripted `beartype.typing.Protocol` superclass *and* parametrizations of that superclass by one or more type variables (e.g., `beartype.typing.Protocol[typing.TypeVar('T')]`) as semantically meaningless in accordance with similar treatment of the `typing.Protocol` superclass. * Permits caller-defined abstract protocols subclassing our caching `beartype.typing.Protocol` superclass to themselves be subclassed by one or more concrete subclasses. Previously, attempting to do so would raise non-human-readable exceptions from the `typing` module; now, doing so behaves as expected. * Relaxed our prior bad assumption that the second-to-last superclass of all generics – and thus protocols – is the `typing.Generic` superclass. That assumption *only* holds for standard generics and protocols; non-standard protocols subclassing non-`typing` superclasses (e.g., the `abc.ABC` superclass) *after* the list `typing` superclass in their method resolution order (MRO) flagrantly violate this assumption. Well, that's fine. We're fine with that. What's not fine about that? **Fine. This is fine.** * Avoids a circular import dependency. Previously, our caching `beartype.typing.Protocol` superclass leveraged the general-purpose `@beartype._util.cache.utilcachecall.callable_cached decorator` to memoize its subscription; however, since that decorator transitively imports from the `beartype.typing` subpackage, doing so induced a circular import dependency. To circumvent this, a new `@beartype.typing._typingcache.callable_cached_minimal` decorator implementing only the minimal subset of the full `@beartype._util.cache.utilcachecall.callable_cached` decorator has been defined; the `beartype.typing` subpackage now safely defers to this minimal variant for all its caching needs. * **[PEP 563][PEP 563] compatibility.** @beartype now resolves [PEP 563][PEP 563]-postponed **self-referential type hints** (i.e., type hints circularly referring to the class currently being decorated). **Caveat:** this support requires that external callers decorate the *class* being referred to (rather than the *method* doing the referring) by the `@beartype` decorator. For this and similar reasons, users are advised to begin refactoring their object-oriented codebases to decorate their *classes* rather than *methods* with `@beartype`. * **[PEP 612][PEP 612] partial shallow compatibility.** @beartype now shallowly detects [PEP 612][PEP 612]-compliant `typing.ParamSpec` objects by internally associating such objects with our `beartype._data.hint.pep.sign.datapepsigns.HintSignParamSpec` singleton, enabling @beartype to portably introspect `Callable[typing.ParamSpec(...), ...]` type hints. * **Static type-checking.** @beartype is now substantially more compliant with static type-checkers, including: * **Microsoft [pyright](https://github.com/microsoft/pyright) + [PyLance](https://marketplace.visualstudio.com/items?itemName=ms-python.vscode-pylance) + [VSCode](https://visualstudio.com).** @beartype now officially supports pyright, Microsoft's in-house static type-checker oddly implemented in pure-TypeScript, <sup>*gulp*</sup> resolving issues beartype#126 and beartype#127 kindly submitted by fellow Zelda aficionado @rbroderi. Specifically, this release resolves several hundred false warnings and errors issued by pyright against the @beartype codebase. It is, indeed, dangerous to go alone – but we did it anyway. * **mypy `beartype.typing.Protocol` compatibility.** The @beartype-specific `beartype.typing.Protocol` superclass implementing [PEP 544][PEP 544]-compliant fast caching protocols is now fully compatible with mypy, Python's official static type-checker. Specifically, `beartype.typing.Protocol` now circumvents: * python/mypy#11013 by explicitly annotating the type of its `__slots__` as `Any`. * python/mypy#9282 by explicitly setting the `typing.TypeVar()` `bounds` parameter to this superclass. * **[PEP 647][PEP 647] compatibility.** @beartype now supports arbitrarily complex **[type narrowing](https://mypy.readthedocs.io/en/latest/type_narrowing.html)** in [PEP 647][PEP 647]-compliant static type-checkers (e.g., mypy, pyright), resolving issues beartype#164 and beartype#165 kindly submitted in parallel by foxy machine learning gurus @justinchuby (Justin Chuby) and @rsokl (Ryan Soklaski). Thanks to their earnest dedication, @beartype is now believed to be the most fully complete type narrower. Specifically, the return of both the `beartype.door.is_bearable()` function and corresponding `beartype.door.TypeHint.is_bearable()` method are now annotated by the [PEP 647][PEP 647]-compliant `typing.TypeGuard[...]` type hint under both Python ≥ 3.10 *and* Python < 3.10 when the optional third-party `typing_extensions` dependency is installed. Doing so substantially reduces false positives from static type checkers on downstream codebases deferring to these callables. Thanks so much for improving @beartype so much, @justinchuby and @rsokl! * **`@{classmethod,staticmethod,property}` chaining.** The `@beartype` decorator now implicitly supports callables decorated by both `@beartype` *and* one of the builtin method decorators `@classmethod`, `@staticmethod`, or `@property` regardless of decoration order, resolving issue beartype#80 kindly requested by @qiujiangkun (AKA, Type Genius-kun). Previously, `@beartype` explicitly raised an exception when ordered *after* one of those builtin method decorators. This releseae relaxes this constraint, enabling callers to list `@beartype` either before or after one of those builtin method decorators. * **`beartype.vale.Is[...]` integration.** Functional validators (i.e., `beartype.vale.Is[...]`) now integrate more cleanly with the remainder of the Python ecosystem, including: * **IPython.** Functional validators localized to a sufficiently intelligent REPL (e.g., IPython) that caches locally defined callables to the standard `linecache` module now raise human-readable errors on type-checking, resolving issue beartype#123 kindly submitted by typing brain-child @braniii. Relatedly, @beartype now permissively accepts both physical on-disk files and dynamic in-memory fake files cached with `linecache` as the files defining an arbitrary callable. * **NumPy,** which publishes various **bool-like tester functions** (i.e., functions returning a non-`bool` object whose class defines at least one of the `__bool__()` or `__len__()` dunder methods and is thus implicitly convertible into a `bool`). Functional validators now support subscription by these functions, resolving issue beartype#153 kindly submitted by molecular luminary @braniii (Daniel Nagel). Specifically, @beartype now unconditionally wraps *all* tester callables subscripting (indexing) `beartype.vale.Is` with a new private `_is_valid_bool()` closure that (in order): 1. Detects when those tester callables return bool-like objects. 2. Coerces those objects into corresponding `bool` values. 3. Returns those `bool` values instead. * **Moar fake builtin types.**@beartype now detects all known **fake builtin types** (i.e., C-based types falsely advertising themselves as being builtin and thus *not* require explicit importation), succinctly resolving issue beartype#158 kindly submitted by the decorous typing gentleman @langfield. Specifically, @beartype now recognizes instances of all of the following as fake builtin types: * `beartype.cave.AsyncCoroutineCType`. * `beartype.cave.AsyncGeneratorCType`. * `beartype.cave.CallableCodeObjectType`. * `beartype.cave.CallableFrameType`. * `beartype.cave.ClassDictType`. * `beartype.cave.ClassType`. * `beartype.cave.ClosureVarCellType`. * `beartype.cave.EllipsisType`. * `beartype.cave.ExceptionTracebackType`. * `beartype.cave.FunctionType`. * `beartype.cave.FunctionOrMethodCType`. * `beartype.cave.GeneratorCType`. * `beartype.cave.MethodBoundInstanceDunderCType`. * `beartype.cave.MethodBoundInstanceOrClassType`. * `beartype.cave.MethodDecoratorBuiltinTypes`. * `beartype.cave.MethodUnboundClassCType`. * `beartype.cave.MethodUnboundInstanceDunderCType`. * `beartype.cave.MethodUnboundInstanceNondunderCType`. * `beartype.cave.MethodUnboundPropertyNontrivialCExtensionType`. * `beartype.cave.MethodUnboundPropertyTrivialCExtensionType`. * **Python 3.6.x support dropped.** This release unilaterally drops support for the Python 3.6.x series, which somnambulantly collided with its End-of-Life (EOL) a year ago and now constitutes a compelling security risk. Doing so substantially streamlines the codebase, whose support for Python 3.6.x required an unmaintainable writhing nest of wicked corner cases. We all now breathe a sigh of contentment in the temporary stillness of morning. * **`beartype.cave` deprecation removals.** This release removes all deprecated third-party attributes from the `beartype.cave` submodule. The continued existence of these attributes substantially increased the cost of importing *anything* from our mostly undocumented `beartype.cave` submodule, rendering that submodule even less useful than it already is. Specifically, this release removes these previously deprecated attributes: * `beartype.cave.NumpyArrayType`. * `beartype.cave.NumpyScalarType`. * `beartype.cave.SequenceOrNumpyArrayTypes`. * `beartype.cave.SequenceMutableOrNumpyArrayTypes`. * `beartype.cave.SetuptoolsVersionTypes`. * `beartype.cave.VersionComparableTypes`. * `beartype.cave.VersionTypes`. * **Colour** – the sensation formerly known as "color." @beartype now emits colourized type-checking violations (i.e., `beartype.roar.BeartypeCallHintViolation` exceptions) raised by both `@beartype`-decorated callables *and* statement-level type-checkers (e.g., `beartype.door.die_if_unbearable()`, `beartype.door.TypeHint.die_if_unbearable()`), resolving issue beartype#161 kindly submitted by foxy machine learning expert @justinchuby (Justin Chu). When standard output is attached to an interactive terminal (TTY), ANSII-flavoured colours now syntactically highlight various substrings of those violations for improved visibility, readability, and debuggability. Since *all* actively maintained versions of Windows (i.e., Windows ≥ 10) now widely support ANSII escape sequences across both Microsoft-managed terminals (e.g., Windows Terminal) and Microsoft-managed Integrated Development Environments (IDEs) (e.g., VSCode), this supports extends to Windows as well. The bad old days of non-standard behaviour are behind us all. Thanks *so* much to @justinchuby for his immense contribution to the righteous cause of eye-pleasing user experience (UX)! * **Types disambiguated.** @beartype now explicitly disambiguates the types of parameters and returns that violate type-checking in exception messages raised by the `@beartype` decorator, resolving issue beartype#124 kindly submitted by typing brain-child @braniii. Thus was justice restored to the QAverse. * **Stack frame squelched.** @beartype now intentionally squelches (i.e., hides) the ignorable stack frame encapsulating the call to our private `beartype._decor._error.errormain.get_beartype_violation()` getter from the parent type-checking wrapper function generated by the :mod:`beartype.beartype` decorator, resolving issue beartype#140 kindly submitted by @langfield (William Blake – yes, *that* William Blake). That stack frame only needlessly complicated visual inspection of type-checking violations in tracebacks – especially from testing frameworks like :mod:`pytest` that recapitulate the full definition of the `get_beartype_violation()` getter (including verbose docstring) in those tracebacks. Specifically, this release: * Renamed the poorly named `raise_pep_call_exception()` function to `get_beartype_violation()` for clarity. * Refactored `get_beartype_violation()` to return rather than raise `BeartypeCallHintViolation` exceptions (while still raising all other types of unexpected exceptions for robustness). * Refactored type-checking wrapper functions to directly raise the exception returned by calling `get_beartype_violation()`. * **``None`` type.** The type of the ``None`` singleton is no longer erroneously labelled as a PEP 544-compliant protocol in type-checking violations. Let's pretend that never happened. * **`beartype.abby.die_if_unbearable()` violations.** The `beartype.abby.die_if_unbearable()` validator function no longer raises non-human-readable exception messages prefixed by the unexpected substring `"@beartyped beartype.abby._abbytest._get_type_checker._die_if_unbearable() return"`. "Surely that never happened, @beartype!" * **`beartype.door.** @beartype now provides a new public framework for introspecting, sorting, and type-checking type hints at runtime in constant time. N-n-now... hear me out here. @leycec came up with a ludicrous acronym and we're going to have to learn to live with it: the **D**ecidedly **O**bject-**O**rientedly **R**ecursive (DOOR) API. Or, `beartype.door` for short. Open the door to a whole new type-hinting world, everyone. `beartype.door` enables type hint arithmetic via an object-oriented type hint class hierarchy encapsulating the crude non-object-oriented type hint declarative API standardized by the :mod:`typing` module, resolving issues beartype#133 and beartype#138 kindly submitted by Harvard microscopist and general genius @tlambert03. The new `beartype.door` subpackage defines a public: * `TypeHint({type_hint})` superclass, enabling rich comparisons between pairs of arbitrary type hints. Altogether, this class implements a partial ordering over the countably infinite set of all type hints. Pedagogical excitement ensues. Instances of this class efficiently satisfy both the `collections.abc.Sequence` and `collections.abc.FrozenSet` abstract base classes (ABC) and thus behave just like tuples and frozen sets over child type hints. Public attributes defined by this class include: * A pair of `die_if_unbearable()` and `is_bearable()` runtime type-checking methods, analogous in behaviour to the existing `beartype.abby.die_if_unbearable()` and `beartype.abby.is_bearable()` runtime type-checking functions. * `TypeHint.is_bearable()`, currently implemented in terms of the procedural `beartype.abby.is_bearable()` tester. * An `is_ignorable` property evaluating to `True` only if the current type hint is semantically ignorable (e.g., `object`, `typing.Any`). There exist a countably infinite number of semantically ignorable type hints. The more you know, the less you want to read this changeset. * The equality comparison operator (e.g., `==`), enabling type hints to be compared according to semantic equivalence. * Rich comparison operators (e.g., `<=`, `>`), enabling type hints to be compared and sorted according to semantic narrowing. * A sane `__bool__()` dunder method, enabling type hint wrappers to be trivially evaluated as booleans according to the child type hints subscripting the wrapped type hints. * A sane `__len__()` dunder method, enabling type hint wrappers to be trivially sized according to the child type hints subscripting the wrapped type hints. * A sane `__contains__()` dunder method, enabling type hint wrappers to be tested for child type hint membership – just like builtin sets, frozen sets, and dictionaries. * A sane `__getindex__()` dunder method, enabling type hint wrappers to be subscripted by both positive and negative indices as well as slices of such indices – just like builtin tuples. * `beartype.door.AnnotatedTypeHint` subclass. * `beartype. 8000 door.CallableTypeHint` subclass. * `beartype.door.LiteralTypeHint` subclass. * `beartype.door.NewTypeTypeHint` subclass. * `beartype.door.TupleTypeHint` subclass. * `beartype.door.TypeVarTypeHint` subclass. * `beartype.door.UnionTypeHint` subclass. * `is_subtype({type_hint_a}, {type_hint_b})` function, enabling @beartype users to decide whether any type hint is a **subtype** (i.e., narrower type hint) of any other type hint. * `beartype.roar.BeartypeDoorNonpepException` type, raised when the `beartype.door.TypeHint` constructor is passed an object that is *not* a PEP-compliant type hint currently supported by the DOOR API. Thanks so much to @tlambert03 for his phenomenal work here. He ran GitHub's PR gauntlet so that you did not have to. Praise be to him. Some people are the living embodiment of quality. @tlambert03 is one such people. * **`beartype.peps`.** @beartype now publicizes runtime support for `typing`-centric Python Enhancement Proposals (PEPs) that currently lack official runtime support via a new public subpackage: `beartype.peps`. Notably, @beartype now provides: . Specifically, this commit: * A new public `beartype.peps.resolve_pep563()` function resolving [PEP 563][PEP 563]-postponed type hints on behalf of third-party Python packages. This function is intended to be "the final word" on runtime resolution of [PEP 563][PEP 563]. May no other third-party package suffer as we have suffered. This commit is for you, everyone. And "by everyone," we of course mostly mean @wesselb of [Plum](github.com/wesselb/plum) fame. See also beartype/plum#53. * **`beartype.vale.Is*[...] {&,|}` short-circuiting.** `&`- and `|`-chained beartype validators now explicitly short-circuit when raising human-readable exceptions from type-checking violations against those validators, resolving issue beartype#125 kindly submitted by typing brain-child @braniii. * **`beartype.abby.is_bearable()` when returning `False`.** Previously, the public `beartype.abby.is_bearable()` runtime type-checker behaved reasonably optimally when the passed object satisfied the passed type hint but *extremely* suboptimally when that object violated that hint; this was due to our current naive implementation of that tester using the standard Easier to Ask for Permission than Forgiveness (EAFP) approach. This release fundamentally refactored `beartype.abby.is_bearable()` in terms of our new private `beartype._check.checkmake.make_func_tester()` type-checking tester function factory function. Ad-hoc profiling shows a speedup on the order of eight orders of magnitude – the single most intense optimization @beartype has ever brought to bear (*heh*). Our core code generation API now transparently generates both: * **Runtime type-checking testers** (i.e., functions merely returning ``False`` on type-checking violations). * **Runtime type-checking validators** (i.e., functions raising exceptions on type-checking violations). * **[PEP 604][PEP 604]-compliant new unions** (e.g., `int | str | None`). Since these unions are **non-self-caching type hints** (i.e., hints that do *not* implicitly cache themselves to reduce space and time consumption), @beartype now efficiently coerces these unions into singletons in the same manner as [PEP 585][PEP 585]-compliant type hints – which are similarly non-self-caching. * **`beartype.abby` → `beartype.door`.** This release officially deprecates the poorly named `beartype.abby` subpackage in favour of the sorta less poorly named `beartype.door` subpackage, whose name actually means something – even if that something is a punny acronym no one will ever find funny. Specifically: * `beartype.abby.die_if_unbearable()` has been moved to `beartype.door.die_if_unbearable()`. * `beartype.abby.is_bearable()` has been moved to `beartype.door.is_bearable()`. To preserve backward compatibility, the `beartype.abby` subpackage continues to dynamically exist (and thus be importable from) – albeit as a deprecated alias of the `beartype.door` subpackage. * **Setuptools licensing.** This release resolves a mostly negligible `setuptools` deprecation warning concerning the deprecated `license_file` setting in the top-level `setup.cfg` file. *Next!* * **[PEP 544][PEP 544] compatibility.** All [PEP 544][PEP 544]-specific test type hints have been generalized to apply to both the non-caching `typing.Protocol` superclass *and* our caching `beartype.typing.Protocol` superclass. * **[PEP 561][PEP 561] compatibility via pyright.** Our test suite now enforces static type-checking with `pyright`. Notably: * A new `test_pep561_pyright` functional test statically type-checks the @beartype codebase against the external `pyright` command in the current `${PATH}` (if available) specific to the version of the active Python interpreter currently being tested. For personal sanity, this test is currently ignored on remote continuous integration (CI) workflows. Let this shrieking demon finally die! * The private `beartype_test.util.cmd.pytcmdrun` submodule underlying our cross-platform portable forking of testing subprocesses now transparently supports vanilla Windows shells (e.g., `CMD.exe`, PowerShell). * **Tarball compatibility.** `beartype` may now be fully tested from non-`git` repositories, including source tarballs containing the `beartype_test` package. Previously, three functional tests making inappropriate assumptions about the existence of a top-level `.git/` directory failed when exercised from a source tarball. * **Sphinx documentation.** Our test suite now exercises that our documentation successfully builds with Sphinx via a new `test_sphinx_build()` functional test. This was surprisingly non-trivial – thanks to the `pytest`-specific `sphinx.testing` subpackage being mostly undocumented, behaving non-orthogonally, and suffering a host of unresolved issues that required we monkey-patch the core `pathlib.Path` class. Insanity, thy name is Sphinx. * **GitHub Actions dependencies bumped.** This release bumps our GitHub Actions-based continuous integration (CI) workflows to both the recently released `checkout@v3` and `setup-python@v3` actions, inspired by a pair of sadly closed PRs by @RotekHandelsGmbH CTO @bitranox (Robert Nowotny). Thanks so much for the great idea, @bitranox! * **`beartype.door` conformance.** A new smoke test guarantees conformance between our DOOR API and abstract base classes (ABCs) published by the standard `typing` module. * **python/mypy#13627 circumvention.** This release pins our GitHub Actions-based CI workflow to Python 3.10.6 rather than 3.10.7, resolving a mypy-specific complaint inducing spurious test failures. * **[`beartype.abby` documented](https://github.com/beartype/beartype#beartype-at-any-time-api).** The new "Beartype At Any Time API" subsection of our front-facing `README.rst` file now documents our public `beartype.abby` API, resolving issue beartype#139 kindly submitted by @gelatinouscube42 (i.e., the user whose username is the answer to the question: "What is the meaning of collagen sustainably harvested from animal body parts?"). * **[GitHub Sponsors activated](https://github.com/sponsors/leycec).** @beartype is now proudly financially supported by **GitHub Sponsors.** Specifically, this release: * Defines a new GitHub-specific funding configuration (i.e., `.github/FUNDING.yml`). * Injects a hopefully non-intrusive advertising template <sup>*gulp*</sup> at the head of our `README.rst` documentation. * **Sphinx configuration sanitized.** As the first tentative step towards chain refactoring our documentation from its current monolithic home in our top-level `README.rst` file to its eventual modular home at [ReadTheDocs (RTD)](https://beartype.readthedocs.io), en-route to resolving issue beartype#8 (!) kindly submitted a literal lifetime ago by visionary computer vision export and long-standing phenomenal Finn @felix-hilden (Felix Hildén): * Our core Sphinx configuration has been resurrected from its early grave – which now actually builds nothing without raising errors. Is this an accomplishment? In 2022, mere survival is an accomplishment! So... *yes.* Significant improvements include: * Activation and configuration of the effectively mandatory `autosectionlabels` builtin Sphinx extension. * Our `doc/source/404.rst` file has been temporarily moved aside, resolving a non-fatal warning pertaining to that file. Look, we're not here to actually solve deep issues; we're here to just get documentation building, which it's not. Sphinx, you have much to answer for. * Our top-level `sphinx` entry point now: * Temporarily disables Sphinx's nit-picky mode (i.e., the `-n` option previously passed to `sphinx-build`) due to Sphinx's `autodoc` extension locally failing to generate working references. * Unconditionally disables Sphinx caching by forcing *all* target documentation files to be rebuilt regardless of whether their underlying source files have since been modified or not, obviating spurious build issues. [PEP 484]: https://www.python.org/dev/peps/pep-0484/ [PEP 544]: https://www.python.org/dev/peps/pep-0544/ [PEP 561]: https://www.python.org/dev/peps/pep-0561/ [PEP 563]: https://www.python.org/dev/peps/pep-0563/ [PEP 585]: https://www.python.org/dev/peps/pep-0585/ [PEP 604]: https://www.python.org/dev/peps/pep-0604/ [PEP 612]: https://www.python.org/dev/peps/pep-0612/ [PEP 647]: https://www.python.org/dev/peps/pep-0647/ (*Impossible journey on an implacable placard-studded gurney!*)
**Beartype 0.10.4** released. This patch release adumbrates with breathless support for **mypy ≥ 0.940,** the static type checker formerly known as "The Static Type Checker Whose Name Shall not Be Spoken." This patch release resolves **5 issues** and merges **0 pull requests.** Noteworthy changes include: * **mypy ≥ 0.940.** The `beartype` codebase now sports improved compatibility with recently released mypy 0.94x series, which previously outted the `@beartype` decorator with a "Condition can't be inferred, unable to merge overloads [misc]" fatal error at static type-checking time. Specifically, this commit fundamentally refactors (and in so doing mildly optimizes) our private `beartype._decor.main` submodule to leverage conditional overloads under the astute tutelage of mypy maestro @cdce8p; the `@beartype.beartype` decorator itself now resides in a new private `beartype._decor.cache.cachedecor` submodule, because obfuscation is the key to all successful open-source efforts. Doing so resolves issues beartype#111 and beartype#112 dual-reported concurrently by cutting-edge Microsoft luminary @daxpryce and German typing bad-ass @twoertwein. * **Importation time.** The first external importation from the `beartype` codebase is now significantly faster when the definition of the `@beartype.beartype` decorator reduces to a noop (e.g., due to `python3 -O` optimization), partially resolves issue beartype#94 kindly requested by the well-tanned and -toned typing star @matanster. * **`beartype.abby` under `python3 -O`.** This release resolves an unreported critical defect in our new functional API (i.e., the pair of `beartype.abby.is_bearable()` and `beartype.abby.die_if_unbearable()` functions), which previously reduced to a noop when the `@beartype.beartype` decorator reduced to a noop (e.g., due to `python3 -O` optimization). By extricating the `@beartype.beartype` decorator into the `beartype._decor.cache.cachedecor` submodule (as described above), our functional API now directly defers to that decorator regardless of what the `beartype` package externally presents to third-party code. (*Ironwrought irony untaught!*)
**Beartype 0.10.3** released. This patch release positively vibrates with superlative support for **functional beartype validators** (i.e., `beartype.vale.Is[...]`). This patch release resolves **5 issues** and merges **2 pull requests.** Noteworthy changes include: * `beartype.vale.Is[@beartype(...)]`.** The functional beartype validator API (i.e., the `beartype.vale.Is[...]` factory) now permissively accepts any low-level callable accepting one parameter wrapped by a higher-level callable, resolving issue beartype#104 kindly submitted by the munificent typing maestro @dycw (Derek Wan). Specifically, the `beartype.vale.Is[...]` factory may now be subscripted (indexed) with any validation function wrapped by a decorator wrapper wrapped by the standard `@functools.wraps` decorator, including any `@beartype`-decorated validation function. Thus is the circle of validation complete. Cue *Hakuna Matata.* * **`setup.py` circularity.** Our top-level `beartype.__init__` submodule no longer implicitly imports from *any* `beartype` submodule (except the guaran 61DB teeably safe `beartype.meta` submodule) when imported at install time by our root `setup.py` script, resolving issue beartype#108 kindly discovered by @posita in a distressing comment embedded within the murky depths of PR beartype#103. Specifically, `setup.py` now dynamically populates the standard `sys.modules` list with a fake `beartype.__is_installing__` "module;" `beartype.__init__` then detects the presence of that "module" and avoids implicitly importing from unsafe `beartype` submodules. In short: insane hackery. That's just how we roll. * **Import isolation.** The `test_package_import_isolation()` integration test minimizing importation costs by ensuring that the first import of the top-level lightweight :mod:`beartype` package does *not* accidentally import from one or more heavyweight third-party packages now omits the third-party `typing_extensions` module from scrutiny. Thanks a bundle of crypto that I do not have to @posita for his deep profiling sacrifice at beartype#103! @posita: *still dah best in 2022.* (*Jubilant sibilance entranced a sigil's brilliance!*)
**Beartype 0.10.2** released. This patch release serves up salacious support for improved compliance with **[PEP 3102 -- Python Keyword-Only Parameters][PEP 3102].** This patch release resolves **1 issue** and merges **0 pull request.** :superscript:`it is sad` Noteworthy changes include: * **[PEP 3102 -- Python Keyword-Only Parameters][PEP 3102]**, resolving issue beartype#102 kindly submitted by stalwart parameter-passing quarterback @dycw (Derek Wan). Previously, `@beartype` only supported optional keyword-only parameters strictly preceding mandatory keyword-only parameters in callable signatures. Now, `@beartype` supports callables whose optional and mandatory keyword-only parameters are heterogeneously mixed in any arbitrary order in callable signatures. * **Argument parsing.** `@beartype` now parses callable signatures significantly faster, thanks to abandoning the extremely inefficient (albeit well-tested) `inspect.signature()` standard parser in favour of our extremely efficient (albeit *not* so well-tested) `beartype._util.func.arg.utilfuncargiter.iter_func_args` home-grown parser -- now believed to be the fastest pure-Python argument parser. Doing so significantly optimizes `@beartype` at decoration time. While still comparatively slow, the `@beartype` decorator is now within two orders of magnitude of the fastest possible decorator (i.e., noop identity decorator). [PEP 3102]: https://www.python.org/dev/peps/pep-3102
PreviousNext