Skip to content

Commit 7b1bdb4

Browse files
committed
Add a few examples of jsonschema.validators.validator_for.
1 parent d830d30 commit 7b1bdb4

File tree

2 files changed

+38
-0
lines changed

2 files changed

+38
-0
lines changed

docs/conf.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -67,6 +67,7 @@ def setup(app):
6767

6868
doctest_global_setup = """
6969
from jsonschema import *
70+
import jsonschema.validators
7071
"""
7172

7273

jsonschema/validators.py

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1141,6 +1141,43 @@ def validator_for(schema, default=_UNSET):
11411141
11421142
If unprovided, the default is to return the latest supported
11431143
draft.
1144+
1145+
Examples:
1146+
1147+
The :kw:`$schema` JSON Schema keyword will control which validator
1148+
class is returned:
1149+
1150+
>>> schema = {
1151+
... "$schema": "https://json-schema.org/draft/2020-12/schema",
1152+
... "type": "integer",
1153+
... }
1154+
>>> jsonschema.validators.validator_for(schema)
1155+
<class 'jsonschema.validators.Draft202012Validator'>
1156+
1157+
1158+
Here, a draft 7 schema instead will return the draft 7 validator:
1159+
1160+
>>> schema = {
1161+
... "$schema": "http://json-schema.org/draft-07/schema#",
1162+
... "type": "integer",
1163+
... }
1164+
>>> jsonschema.validators.validator_for(schema)
1165+
<class 'jsonschema.validators.Draft7Validator'>
1166+
1167+
1168+
Schemas with no ``$schema`` keyword will fallback to the default
1169+
argument:
1170+
1171+
>>> schema = {"type": "integer"}
1172+
>>> jsonschema.validators.validator_for(
1173+
... schema, default=Draft7Validator,
1174+
... )
1175+
<class 'jsonschema.validators.Draft7Validator'>
1176+
1177+
or if none is provided, to the latest version supported.
1178+
Always including the keyword when authoring schemas is highly
1179+
recommended.
1180+
11441181
"""
11451182

11461183
DefaultValidator = _LATEST_VERSION if default is _UNSET else default

0 commit comments

Comments
 (0)