Package: beartype
⚠Beartype documentation lives at ReadTheDocs (RTD). It’s
readable, structured, and soothing to the deep folds of your big galactic
brain. Open your mind to an ocean of mundane knowledge that will exhaust
you at work. Enter…the Bearpedia:https://beartype.readthedocs.ioThe document you are now reading was once a monolithic ~316Kb file known to
induce migraines in 22% of the whole devops population. For your safety,
that document no longer exists. This is how much beartype cares.Beartypeis anopen-sourcepure-PythonPEP-compliantnear-real-timehybrid runtime-staticthird-generationtype checkeremphasizing efficiency,
usability, unsubstantiated jargon we just made up, and thrilling puns.# Install beartype.$pip3installbeartype# Edit the "{your_package}.__init__" submodule with your favourite IDE.$vim{your_package}/__init__.py# <-- so, i see that you too vimfrombeartype.clawimportbeartype_this_package# <-- hype comesbeartype_this_package()# <-- hype goesBeartype now implicitly type-checksallannotated classes, callables, and
variable assignments acrossallsubmodules of your package. Congrats. This day
all bugs die.But why stop at the burning tires in onlyyourcode? Your app depends on a
sprawling ghetto of other packages, modules, and services. How riddled with
infectious diseases isthatcode? You’re about to find out.# ....................{ BIG BEAR                        }....................# Warn about type hint violations in *OTHER* packages outside your control;# only raise exceptions from violations in your package under your control.# Again, at the very top of your "{your_package}.__init__" submodule:frombeartypeimportBeartypeConf# <-- this isn't your faultfrombeartype.clawimportbeartype_all,beartype_this_package# <-- you didn't sign up for thisbeartype_this_package()# <-- raise exceptions in your codebeartype_all(conf=BeartypeConf(violation_type=UserWarning))# <-- emit warnings from other codeBeartype now implicitly type-checksallannotated classes, callables, and
variable assignments acrossallsubmodules ofallpackages. Whenyourpackage violates type safety, beartype raises an exception. When anyotherpackage violates type safety, beartype just emits a warning. The triumphal
fanfare you hear is probably your userbase cheering. This is how the QA was won.Beartype also publishes aplethora of APIs for fine-grained control over
type-checking <beartype APIs>. For those who are about to QA, beartype salutes
you. Would you like to know more?# So let’s do this.
$ python3# ....................{ RAISE THE PAW                   }....................# Manually enforce type hints across individual classes and callables.# Do this only if you want a(nother) repetitive stress injury.# Import the @beartype decorator.>>>frombeartypeimportbeartype# <-- eponymous import; it's eponymous# Annotate @beartype-decorated classes and callables with type hints.>>>@beartype# <-- you too will believe in magic...defquote_wiggum(lines:list[str])->None:...print('“{}”\n\t— Police Chief Wiggum'.format("\n".join(lines)))# Call those callables with valid parameters.>>>quote_wiggum(["Okay, folks. Show's over!"," Nothing to see here. Show's…",])“Okay,folks.Show's over!Nothingtoseehere.Show's…”—PoliceChiefWiggum# Call those callables with invalid parameters.>>>quote_wiggum([b"Oh, my God! A horrible plane crash!",b"Hey, everybody! Get a load of this flaming wreckage!",])Traceback(mostrecentcalllast):File"<stdin>",line1,in<module>File"<string>",line30,inquote_wiggumFile"/home/springfield/beartype/lib/python3.9/site-packages/beartype/_decor/_code/_pep/_error/errormain.py",line220,inget_beartype_violationraiseexception_cls(beartype.roar.BeartypeCallHintParamViolation:@beartypedquote_wiggum()parameterlines=[b'Oh, my God! A horrible planecrash!', b'Hey,everybody!Getaloadofthi...'] violates type hintlist[str],aslistitem0valueb'Oh, my God! A horrible plane crash!'notstr.# ....................{ MAKE IT SO                      }....................# Squash bugs by refining type hints with @beartype validators.>>>frombeartype.valeimportIs# <---- validator factory>>>fromtypingimportAnnotated# <---------------- if Python ≥ 3.9.0# >>> from typing_extensions import Annotated   # <-- if Python < 3.9.0# Validators are type hints constrained by lambda functions.>>>ListOfStrings=Annotated[# <----- type hint matching non-empty list of strings...list[str],# <----------------- type hint matching possibly empty list of strings...Is[lambdalst:bool(lst)]# <-- lambda matching non-empty object...]# Annotate @beartype-decorated callables with validators.>>>@beartype...defquote_wiggum_safer(lines:ListOfStrings)->None:...print('“{}”\n\t— Police Chief Wiggum'.format("\n".join(lines)))# Call those callables with invalid parameters.>>>quote_wiggum_safer([])beartype.roar.BeartypeCallHintParamViolation:@beartypedquote_wiggum_safer()parameterlines=[]violatestypehinttyping.Annotated[list[str],Is[lambdalst:bool(lst)]],asvalue[]violatesvalidatorIs[lambdalst:bool(lst)].# ....................{ AT ANY TIME                     }....................# Type-check anything against any type hint – anywhere at anytime.>>>frombeartype.doorimport(...is_bearable,# <-------- like "isinstance(...)"...die_if_unbearable,# <-- like "assert isinstance(...)"...)>>>is_bearable(['The','goggles','do','nothing.'],list[str])True>>>die_if_unbearable([0xCAFEBEEF,0x8BADF00D],ListOfStrings)beartype.roar.BeartypeDoorHintViolation:Object[3405692655,2343432205]violatestypehinttyping.Annotated[list[str],Is[lambdalst:bool(lst)]],aslistindex0item3405692655notinstanceofstr.# ....................{ GO TO PLAID                     }....................# Type-check anything in around 1µs (one millionth of a second) – including# this list of one million 2-tuples of NumPy arrays.>>>frombeartype.doorimportis_bearable>>>fromnumpyimportarray,ndarray>>>data=[(array(i),array(i))foriinrange(1000000)]>>>%timeis_bearable(data,list[tuple[ndarray,ndarray]])CPUtimes:user31µs,sys:2µs,total:33µsWalltime:36.7µsTrueBeartype bringsRust- andC++-inspiredzero-cost abstractionsinto the lawless world ofdynamically-typedPython byenforcing type safety at the granular level of functions and methodsagainsttype hints standardized by the Python communityinO(1) non-amortized worst-case time with negligible constant
factors. If the prior sentence was unreadable jargon,see
our friendly and approachable FAQ for a human-readable synopsis.Beartype isportably implementedinPython 3,continuously stress-testedviaGitHub
Actions×tox×pytest×Codecov, andpermissively
distributedunder theMIT license. Beartype hasnoruntime dependencies,only one test-time dependency, andonly
one documentation-time dependency. Beartype supportsall actively
developed Python versions,all Python package managers, andmultiple platform-specific package managers.