A small extendable python type checker library
Project description
simple_type_checker
A small extendable python type checker library
Basic Usage
Checking a type:
from simple_type_checker import type_check
assert type_check("A string", str)
As a decorator:
from simple_type_checker import type_check, TypeCheckFailed
@type_check.returns
def id_(x) -> int:
return x
_ = id_(1) # Passes
try:
id_("string")
except TypeCheckFailed as e:
print("Bad input: ", e)
Decorators for aruments exist as well: type_check.args
.
Both can be done at once with type_check.decorate
.
With custom types
Basic types where isinstance
is sufficient:
from simple_type_checker import TypeChecker
class Foo:
pass
type_check = TypeChecker(Foo)
assert type_check(Foo(), Foo)
Special type checking logic desired
from simple_type_checker import TypeChecker, Checker
class Bar:
def __init__(self, b):
self.can_check = b
class CheckerBar(Checker):
def __call__(self, obj: Any, type_: Any) -> bool:
return type_ == Bar and isinstance(obj, Bar) and obj.can_check
type_check = TypeChecker(advanced=(Bar,))
assert type_check(Bad(True), Bar)
assert not type_check(Bad(False), Bar)
This use case is useful for container types that take arguments, for example.
Failures
This will may work with quoted type annotations without adding a custom type Checker. For example, the following will fail:
from simple_type_checker import type_check
Bar = list[int | "Bar"]
@type_check.returns
def f() -> Bar:
return []
This is because no type checker knows what "MyType" is.
Fixing this is as easy as adding a custom Checker that accepts "MyType" as a valid type, as demonstrated with CheckerBar
above.
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
File details
Details for the file simple_type_checker-2.1.1.tar.gz
.
File metadata
- Download URL: simple_type_checker-2.1.1.tar.gz
- Upload date:
- Size: 19.3 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/4.0.2 CPython/3.11.7
File hashes
Algorithm | Hash digest | |
---|---|---|
SHA256 | 7b429968025d00007e57a6a5ed37520e58af5c7736c395dd1a6c3cf77f5d2027 |
|
MD5 | 45522ee4fbc3e946d5bc8b2e3765753a |
|
BLAKE2b-256 | 146688b48b5ab87d08ed755c0816186d544f11ac93ee62ac200c9065dbf4f336 |
File details
Details for the file simple_type_checker-2.1.1-py3-none-any.whl
.
File metadata
- Download URL: simple_type_checker-2.1.1-py3-none-any.whl
- Upload date:
- Size: 20.3 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/4.0.2 CPython/3.11.7
File hashes
Algorithm | Hash digest | |
---|---|---|
SHA256 | 15fcd29c851e2961ec19b4232258adb3af0aad4ee8c550d4c98f9cff62b48543 |
|
MD5 | dd4fd4aae9631944a709f6e1c4280a20 |
|
BLAKE2b-256 | fedf7cb8af0f1e000d2fc1e5517de91389495613819011777a72083946486cc1 |