Skip to content

Instantly share code, notes, and snippets.

@kashifpk
Created February 18, 2024 09:15
Show Gist options
  • Save kashifpk/890632a2a38cda8283682591f066448b to your computer and use it in GitHub Desktop.
Save kashifpk/890632a2a38cda8283682591f066448b to your computer and use it in GitHub Desktop.
Dynamic model creation using pydantic
from pydantic import create_model
fields = [
{'field_name': 'name', 'field_type': str, 'default': ''},
{'field_name': 'age', 'field_type': int, 'default': 100}
]
MyModel = create_model(
'MyModel',
**{field['field_name']: (field['field_type'], field['default']) for field in fields}
)
m = MyModel(name='Ilya', age=35)
m.model_dump()
# {'name': 'Ilya', 'age': 35}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment