Skip to content

Commit

Permalink
Handle a case when model_config is defined as a model property (#9004)
Browse files Browse the repository at this point in the history
  • Loading branch information
alexeyt101 committed Mar 17, 2024
1 parent 325ddf6 commit 1cfb22e
Show file tree
Hide file tree
Showing 4 changed files with 46 additions and 0 deletions.
15 changes: 15 additions & 0 deletions docs/errors/usage_errors.md
Expand Up @@ -1089,4 +1089,19 @@ pydantic.errors.PydanticUserError: Dataclass field bar has init=False and init_v
"""
```

## `model_config` is used as a model field {#model-config-invalid-field-name}

This error is raised when `model_config` is used as the name of a field.
```py
from pydantic import BaseModel, PydanticUserError

try:

class Model(BaseModel):
model_config: str

except PydanticUserError as exc_info:
assert exc_info.code == 'model-config-invalid-field-name'
```

{% endraw %}
7 changes: 7 additions & 0 deletions pydantic/_internal/_config.py
Expand Up @@ -116,6 +116,13 @@ def for_model(cls, bases: tuple[type[Any], ...], namespace: dict[str, Any], kwar
config_class_from_namespace = namespace.get('Config')
config_dict_from_namespace = namespace.get('model_config')

raw_annotations = namespace.get('__annotations__', {})
if raw_annotations.get('model_config') and not config_dict_from_namespace:
raise PydanticUserError(
'`model_config` cannot be used as a model field name. Use `model_config` for model configuration.',
code='model-config-invalid-field-name',
)

if config_class_from_namespace and config_dict_from_namespace:
raise PydanticUserError('"Config" and "model_config" cannot be used together', code='config-both')

Expand Down
1 change: 1 addition & 0 deletions pydantic/errors.py
Expand Up @@ -61,6 +61,7 @@
'unevaluable-type-annotation',
'dataclass-init-false-extra-allow',
'clashing-init-and-init-var',
'model-config-invalid-field-name',
]


Expand Down
23 changes: 23 additions & 0 deletions tests/test_config.py
Expand Up @@ -796,3 +796,26 @@ def create_partial(model, optionals):

# AssertionError: assert ['a', 'b'] == ['b']
assert partial.model_json_schema()['required'] == ['b']


def test_model_config_as_model_field_raises():
with pytest.raises(PydanticUserError) as exc_info:

class MyModel(BaseModel):
model_config: str

assert exc_info.value.code == 'model-config-invalid-field-name'


def test_dataclass_allowes_model_config_as_model_field():
config_title = 'from_config'
field_title = 'from_field'

@pydantic_dataclass(config={'title': config_title})
class MyDataclass:
model_config: dict

m = MyDataclass(model_config={'title': field_title})

assert m.model_config['title'] == field_title
assert getattr(m, '__pydantic_config__')['title'] == config_title

0 comments on commit 1cfb22e

Please sign in to comment.