Use `TypedDict` replace pydantic definitions.
Project description
TypedDict
Use TypedDict
replace pydantic definitions.
Why?
from pydantic import BaseModel
class User(BaseModel):
name: str
age: int = Field(default=0, ge=0)
email: Optional[str]
user: User = {"name": "John", "age": 30} # Type check, error!
print(repr(user))
In index.py or other framework, maybe you write the following code. And then got an type check error in Annotated[Message, ...]
, because the type of {"message": "..."}
is not Message
.
class Message(BaseModel):
message: str
@routes.http.get("/user")
async def create_user(
...
) -> Annotated[Message, JSONResponse[200, {}, Message]]:
...
return {"message": "Created successfully!"}
Usage
Use Annotated
to provide extra information to pydantic.Field
. Other than that, everything conforms to the general usage of TypedDict
. Using to_pydantic
will create a semantically equivalent pydantic model. You can use it in frameworks like index.py / fastapi / xpresso.
from typing_extensions import TypedDict, NotRequired, Annotated
import typeddict
from typeddict import Metadata, Extra
class User(TypedDict):
name: str
age: Annotated[int, Metadata(default=0), Extra(ge=0)]
email: NotRequired[str]
user: User = {"name": "John", "age": 30} # Type check, pass!
print(repr(user))
# Then use it in index.py / fastapi or other frameworks
UserModel = typeddict.to_pydantic(User)
print(repr(UserModel.parse_obj(user)))
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
typeddict-0.1.0.tar.gz
(7.3 kB
view hashes)
Built Distribution
Close
Hashes for typeddict-0.1.0-py3-none-any.whl
Algorithm | Hash digest | |
---|---|---|
SHA256 | 037c37e17022893dcb9ced3ced7572250991c7084e886822fe24cabfcc640b0c |
|
MD5 | 47c2a25c9c580f8f4c17ac5090b05623 |
|
BLAKE2b-256 | 8e208617916376cd442f5ddb0afbfac68c1a7abc0bd512b4f0a21ea8ae3a5628 |