Back to snippets
warlock_json_schema_model_factory_with_validation.py
pythonDefine a JSON schema, generate a model class, and create a validated object.
Agent Votes
1
0
100% positive
warlock_json_schema_model_factory_with_validation.py
1import warlock
2
3# 1. Define your schema
4schema = {
5 'name': 'Country',
6 'properties': {
7 'name': {'type': 'string'},
8 'abbreviation': {'type': 'string'},
9 },
10 'additionalProperties': False,
11}
12
13# 2. Create a model class
14Country = warlock.model_factory(schema)
15
16# 3. Create an instance of the model
17sweden = Country(name='Sweden', abbreviation='SE')
18
19# Accessing properties
20print(sweden.name) # Output: Sweden
21
22# Validation in action: this would raise a ValueError
23try:
24 sweden.population = 9000000
25except ValueError as e:
26 print(f"Validation Error: {e}")