Runtime-type-checker performs type check at runtime with help of type annotations
Project description
This package performs type-check at runtime with help of type annotations.
How to use this package
There are two ways to perform type checks using this package.
I provide a few simple examples here. For a complete overview, have a look at the package's unit tests.
1- the check_type
function
You can check an object against a type or an annotation via the check_type
function.
The function returns None
if the check was successful or raises a TypeError
in case of error.
Note that this function does not check recursively for e.g. the attributes of a class.
from dataclasses import dataclass
from runtime_type_checker import check_type
check_type("a", str) # OK
check_type(["a"], List[str]) # OK
check_type(["a", 1], Sequence[str]) # raises TypeError
@dataclass
Foo:
a: int
b: Optional[Mapping[str, int]] = None
check_type(Foo(1), Foo) # OK
check_type(Foo(1), int) # raises TypeError
2- The check_types decorator
You can also type-check classes upon instance creation and functions or methods upon call through the check_types
decorator:
from dataclasses import dataclass
from runtime_type_checker import check_types
@check_types
@dataclass
Foo:
a: int
b: Optional[Mapping[str, int]] = None
Foo(1) # returns an instance of foo
Foo(0, {"a": "b"}) # raises TypeError
@check_types
def bar(a: bool, **options: str) -> str:
return options.get("b", "missing") if a else "unknown"
bar(True, b="1") # returns "1"
bar(True, c=1) # raises TypeError
Package features and short-comings
1- Features
- simplicity: there's only one function and one decorator to keep in mind.
- robustness: this package relies on the
typing-inspect
for the heavy lifting. This package is maintained by core contributors to the typing module, which means very little hacks on my side to work with older versions of python.
2- Short-comings
- coverage: I don't offer coverage for all features of type annotations: for example Protocol, Generators, IO are not currently supported. Generics are not really well handled.
Project details
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Hashes for runtime-type-checker-0.2.0.tar.gz
Algorithm | Hash digest | |
---|---|---|
SHA256 | 2ed0b0114061ae79f1617ce13f9d305fa1cb5249cca72976a17993d78ccdda82 |
|
MD5 | 7f8644ac593cd9eb683522320c98c886 |
|
BLAKE2b-256 | b6f4e5effafc03b8eaf48e82c7be12cdd969c0295075e480a5c09ccf37a34b57 |
Hashes for runtime_type_checker-0.2.0-py3-none-any.whl
Algorithm | Hash digest | |
---|---|---|
SHA256 | 026418eea7216c023fc2dde20c64623f538cfb03095a5c037401c1b44f9da725 |
|
MD5 | d03445aeb203e0ea7625d06d8cc55d26 |
|
BLAKE2b-256 | e2b08c22a61304e995ca52846c38f41ca3c953a99d52cfcf7bfa5b173cd8736d |