Last active
May 11, 2023 08:55
-
-
Save viniciusao/6aeb5b176f593c3a23a4ff4e103c27bc to your computer and use it in GitHub Desktop.
Dynamic pydantinc model creation
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
from pydantic import create_model | |
def create_pydantic_model(name: str, **kwargs): | |
""" | |
Create a pydantic model. | |
:param name: name of the BaseModel class to create. | |
:param kwargs: BaseModel' fields. | |
""" | |
pydantic_model = create_model(name, **kwargs) | |
def func_decorator(function): | |
def wrapper(*args, **kwargs): | |
func_fields_values = [*args, *kwargs.values()] | |
keys_to_values = zip(pydantic_model.__fields__.keys(), func_fields_values,) | |
set_func_fields_values = {x: y for x, y in keys_to_values} | |
func_model = pydantic_model(**set_func_fields_values) | |
return function(*args, **kwargs, model_=func_model) | |
return wrapper | |
return func_decorator | |
@create_pydantic_model('FunctionNumber100', a=(int, ...), b=(int, 1)) | |
def function_number_100(x: int, *, y: int, **kwargs,): | |
model_ = kwargs.pop('model_') | |
sum_ = model_.a + model_.b | |
assert sum_ == 3 and model_.a == 1 and model_.b == 2 | |
function_number_100(1, y=2) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment