Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Apply __modify_schema__ on enum schema rather than fields that use it #1581

Merged
merged 3 commits into from Jun 29, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
1 change: 1 addition & 0 deletions changes/1581-therefromhere.md
@@ -0,0 +1 @@
Make `__modify_schema__` on Enums apply to the enum schema rather than fields that use the enum.
10 changes: 7 additions & 3 deletions pydantic/schema.py
Expand Up @@ -545,6 +545,10 @@ def enum_process_schema(enum: Type[Enum]) -> Dict[str, Any]:

add_field_type_to_schema(enum, schema)

modify_schema = getattr(enum, '__modify_schema__', None)
if modify_schema:
modify_schema(schema)

return schema


Expand Down Expand Up @@ -698,9 +702,9 @@ def field_singleton_schema( # noqa: C901 (ignore complexity)
else:
add_field_type_to_schema(field_type, f_schema)

modify_schema = getattr(field_type, '__modify_schema__', None)
if modify_schema:
modify_schema(f_schema)
modify_schema = getattr(field_type, '__modify_schema__', None)
if modify_schema:
modify_schema(f_schema)

if f_schema:
return f_schema, definitions, nested_models
Expand Down
28 changes: 28 additions & 0 deletions tests/test_schema.py
Expand Up @@ -222,6 +222,34 @@ class Model(BaseModel):
}


def test_enum_modify_schema():
class SpamEnum(str, Enum):
foo = 'f'
bar = 'b'

@classmethod
def __modify_schema__(cls, field_schema):
field_schema['tsEnumNames'] = [e.name for e in cls]

class Model(BaseModel):
spam: SpamEnum = Field(None)

assert Model.schema() == {
'definitions': {
'SpamEnum': {
'description': 'An enumeration.',
'enum': ['f', 'b'],
'title': 'SpamEnum',
'tsEnumNames': ['foo', 'bar'],
'type': 'string',
}
},
'properties': {'spam': {'$ref': '#/definitions/SpamEnum'}},
'title': 'Model',
'type': 'object',
}


def test_json_schema():
class Model(BaseModel):
a = b'foobar'
Expand Down