Files
pydantic/docs/examples/dataclasses_stdlib_to_pydantic.py
Eric Jolibois 576e4a3a8d refactor: change pydantic dataclass decorator (#2557)
* refactor: rewrite the whole pydantic dataclass logic

* test: add tests for issue 2162

* test: add tests for issue 2383

* test: add tests for issue 2398

* test: add tests for issue 2424

* test: add tests for issue 2541

* test: add tests for issue 2555

* refactor: polish

* change default and support 3.6

* fix coverage

* fix mypy and text

* typos

* test: add tests for issue 2594

* fix: forward doc for schema description

* add change

* chore: small changes from review

* refactor: avoid extra __pydantic_run_validation__ parameter

* small tweaks

* remove wrapper

* support 3.6

* fix: mypy

* rewrite doc

* add docs

* wrapper is removed now

* a bit more docs

* code review

* faster dict update

* add test for issue 3162

* add test for issue 3011

* feat: add `Config.post_init_after_validation`

* allow config via dict

* fix cython and TypedDict

* chore: typo

* move `compiled` in `version.py`

* refactor: switch from `Config.post_init_after_validation` to \'post_init_call`

* add dataclass isinstance support

* avoid multi paragraphs in change file

* feat: support `Config.extra`

* refactor: simplify a bit code

* refactor: avoid creating useless functions

* refactor: simplify `is_builtin_dataclass`

* support extra in post_init

* docs: add warning on config extra

* fix #3713 compatibility

* update docs

Co-authored-by: Samuel Colvin <s@muelcolvin.com>
2022-08-04 12:06:54 +01:00

48 lines
932 B
Python

import dataclasses
from datetime import datetime
from typing import Optional
import pydantic
@dataclasses.dataclass
class Meta:
modified_date: Optional[datetime]
seen_count: int
@dataclasses.dataclass
class File(Meta):
filename: str
# `ValidatedFile` will be a proxy around `File`
ValidatedFile = pydantic.dataclasses.dataclass(File)
# the original dataclass is the `__dataclass__` attribute
assert ValidatedFile.__dataclass__ is File
validated_file = ValidatedFile(
filename=b'thefilename',
modified_date='2020-01-01T00:00',
seen_count='7',
)
print(validated_file)
try:
ValidatedFile(
filename=['not', 'a', 'string'],
modified_date=None,
seen_count=3,
)
except pydantic.ValidationError as e:
print(e)
# `File` is not altered and still does no validation by default
print(File(
filename=['not', 'a', 'string'],
modified_date=None,
seen_count=3,
))