Created
October 10, 2025 19:44
-
-
Save robmurrer/77443a5a6ea5d1139a945d77fd594611 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import time | |
| from typing import Callable | |
| from pydantic import BaseModel, Field, ConfigDict | |
| class ShapePure(object): | |
| shape: str | |
| perimeter: float | |
| area: float | |
| def __init__(self, shape: str, perimeter: float, area: float): | |
| self.shape = shape | |
| self.perimeter = perimeter | |
| self.area = area | |
| class ShapeLoose(BaseModel): | |
| shape: str | |
| perimeter: float | |
| area: float | |
| class StrictModel(BaseModel): | |
| model_config = ConfigDict(strict=True, validate_assignment=True) # makes all fields strict | |
| pass | |
| class ShapeStrict(StrictModel): | |
| shape: str | |
| perimeter: float | |
| area: float | |
| def timeit_loop(func: Callable, loop_count=int(1e6)) -> float: | |
| start = time.perf_counter() | |
| for i in range(loop_count): | |
| func() | |
| return time.perf_counter() - start | |
| pure_init = lambda: ShapePure(shape='a', perimeter=1, area=1) | |
| print('pure init', timeit_loop(pure_init)) | |
| loose_init = lambda: ShapeLoose(shape='a', perimeter=1, area=1) | |
| print('loose init', timeit_loop(loose_init)) | |
| strict_init = lambda: ShapeStrict(shape='a', perimeter=1, area=1) | |
| print('strict init', timeit_loop(strict_init)) | |
| def attr_set(obj): | |
| obj.shape = 'yeet' | |
| def func_no_args(func: Callable, obj) -> Callable: | |
| def wrapped(): | |
| return func(obj) | |
| return wrapped | |
| print('pure set', timeit_loop(func_no_args(attr_set, pure_init()))) | |
| print('loose set', timeit_loop(func_no_args(attr_set, loose_init()))) | |
| print('strict set', timeit_loop(func_no_args(attr_set, strict_init()))) | |
| #x = Shape(shape="tri-angel", perimeter=3.0, area=5) | |
| #print(x) # shape='tri-angel' perimeter=3.0 area=5.0 | |
| #x.shape = 10.0 # now is a runtime error | |
| #x.hello = "10" # runtime error as expected | |
| #/Users/serf/deve/pyground2025/.venv/bin/python /Users/serf/deve/pyground2025/pydantic_tests.py | |
| #pure init 0.12748912499955622 | |
| #loose init 0.4202396670007147 | |
| #strict init 0.42075450000265846 | |
| #pure set 0.03571079199900851 | |
| #loose set 0.13500008299888577 | |
| #trict set 0.40960837499733316 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment