Created
February 18, 2024 09:15
-
-
Save kashifpk/890632a2a38cda8283682591f066448b to your computer and use it in GitHub Desktop.
Dynamic model creation using pydantic
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 | |
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