Skip to content

Commit

Permalink
Allow dicts to have both patternProperties and additionalProperties
Browse files Browse the repository at this point in the history
Support for `patternProperties` was introduced in #332, but that logic
unfortunately made `patternProperties` and `additionalProperties`
mutually exclusive. JSON Schema supports their combination:

https://json-schema.org/understanding-json-schema/reference/object.html#additional-properties

This prevented well-typed code generation for dictionaries that use
regex-constrained string keys.
  • Loading branch information
jparise committed Oct 22, 2022
1 parent b516de7 commit 8289c12
Show file tree
Hide file tree
Showing 3 changed files with 9 additions and 2 deletions.
1 change: 1 addition & 0 deletions changes/4641-jparise.md
@@ -0,0 +1 @@
Allow dict schemas to have both `patternProperties` and `additionalProperties`
2 changes: 1 addition & 1 deletion pydantic/schema.py
Expand Up @@ -490,7 +490,7 @@ def field_type_schema(
# Dict keys have a regex pattern
# items_schema might be a schema or empty dict, add it either way
f_schema['patternProperties'] = {regex.pattern: items_schema}
elif items_schema:
if items_schema:
# The dict values are not simply Any, so they need a schema
f_schema['additionalProperties'] = items_schema
elif field.shape == SHAPE_TUPLE or (field.shape == SHAPE_GENERIC and not issubclass(field.type_, BaseModel)):
Expand Down
8 changes: 7 additions & 1 deletion tests/test_schema.py
Expand Up @@ -1654,7 +1654,13 @@ class Foo(BaseModel):
'title': 'Foo',
'type': 'object',
'properties': {
'a': {'type': 'object', 'title': 'A', 'default': {}, 'patternProperties': {regex_str: {'type': 'string'}}}
'a': {
'type': 'object',
'title': 'A',
'default': {},
'additionalProperties': {'type': 'string'},
'patternProperties': {regex_str: {'type': 'string'}},
}
},
}

Expand Down

0 comments on commit 8289c12

Please sign in to comment.