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.3.tar.gz
.
File metadata
- Download URL: tenforce-0.1.3.tar.gz
- Upload date:
- Size: 60.6 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/4.0.2 CPython/3.11.3
File hashes
Algorithm | Hash digest | |
---|---|---|
SHA256 | 35cdf101b632056e1b6ba9f828070d592f77fddfc5f6bf59741898cfaa36e402 |
|
MD5 | e0dae09c2495c9680aadf410cd1c5aa5 |
|
BLAKE2b-256 | ec1ba4c12bd7a800e41e3391b9a418acc420b17b1503cba92d11a6e7cf7665af |