Type enforcement for Python
Project description
Tenforce
Type enforcement for Python.
Installation
pip install tenforce
Usage
from uuid import UUID, uuid4
from tenforce.enforcer import check
# define a class
class CreateOrderRequest:
user_id: UUID
skus: list[int]
ship_service_level: str
if __name__ == "__main__":
# populate your class that needs type enforcement
request = CreateOrderRequest()
request.user_id = uuid4()
request.skus = [1234567890, 0987213]
ship_service_level = "Overnight"
# call check() on it
check(request)
# or, automatically cast compatible types (ex: numeric strings with an int annotation)
check(request, auto_cast=True)
Reason for development
I developed this package because I had issues with Pydantic and handling large amounts of base models. I eventually
plan to add serialization/deserialization to this. For example, populating one billion BaseModel
objects in
Pydantic takes roughly 30-35 seconds on my M1 Mac, versus 3-7 seconds with Tenforce. Pydantic is supposed to get a
rewrite in rust with V2 though, so let's see how that turns out :)
Results
Principles
This package is designed to enforce the types of a Python class and its class variables (through type hints). Written mainly in Cython, it follows a few design principles.
- Sacrifice certain dynamic language features for speed and simplicity
- Things like Unions (except for
None
unions &Optional
) & subscripted type annotations (ex:list[str]
) for the sake of simplicity and speed
- Things like Unions (except for
- Opt-in helpers, not opt-out
- By default, we try to run was little code as possible when calling
check()
on an object. We do have extra arguments likeauto_cast
to automatically cast variables (assuming it can be a successful cast)
- By default, we try to run was little code as possible when calling
- Support only the most popular patterns for API development
- In my experience doing backend in a dynamic language such as Python, it is often you don't find yourself ever needing
a list able to contain multiple types (ex:
list[str | int]
) - Building in lots of features will inevitably add slowdowns to
check()
- In my experience doing backend in a dynamic language such as Python, it is often you don't find yourself ever needing
a list able to contain multiple types (ex:
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
File details
Details for the file tenforce-0.1.4.tar.gz
.
File metadata
- Download URL: tenforce-0.1.4.tar.gz
- Upload date:
- Size: 148.5 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/4.0.2 CPython/3.11.3
File hashes
Algorithm | Hash digest | |
---|---|---|
SHA256 | e77e38bbd70ff256cbe084151fe04f84ddefc51659f821d612cd77c9a8ea29d3 |
|
MD5 | 952870a6d61f6aa6ae81d2830da46bcb |
|
BLAKE2b-256 | 176475dfd97fc8878e74e3ef680aada5551d7be3929f19a899c1154cdf15c908 |