config.py 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. from __future__ import annotations as _annotations
  2. import warnings
  3. from typing import TYPE_CHECKING, Any
  4. from typing_extensions import Literal, deprecated
  5. from .._internal import _config
  6. from ..warnings import PydanticDeprecatedSince20
  7. if not TYPE_CHECKING:
  8. # See PyCharm issues https://youtrack.jetbrains.com/issue/PY-21915
  9. # and https://youtrack.jetbrains.com/issue/PY-51428
  10. DeprecationWarning = PydanticDeprecatedSince20
  11. __all__ = 'BaseConfig', 'Extra'
  12. class _ConfigMetaclass(type):
  13. def __getattr__(self, item: str) -> Any:
  14. warnings.warn(_config.DEPRECATION_MESSAGE, DeprecationWarning)
  15. try:
  16. return _config.config_defaults[item]
  17. except KeyError as exc:
  18. raise AttributeError(f"type object '{self.__name__}' has no attribute {exc}") from exc
  19. @deprecated('BaseConfig is deprecated. Use the `pydantic.ConfigDict` instead.', category=PydanticDeprecatedSince20)
  20. class BaseConfig(metaclass=_ConfigMetaclass):
  21. """This class is only retained for backwards compatibility.
  22. !!! Warning "Deprecated"
  23. BaseConfig is deprecated. Use the [`pydantic.ConfigDict`][pydantic.ConfigDict] instead.
  24. """
  25. def __getattr__(self, item: str) -> Any:
  26. warnings.warn(_config.DEPRECATION_MESSAGE, DeprecationWarning)
  27. try:
  28. return super().__getattribute__(item)
  29. except AttributeError as exc:
  30. try:
  31. return getattr(type(self), item)
  32. except AttributeError:
  33. # re-raising changes the displayed text to reflect that `self` is not a type
  34. raise AttributeError(str(exc)) from exc
  35. def __init_subclass__(cls, **kwargs: Any) -> None:
  36. warnings.warn(_config.DEPRECATION_MESSAGE, DeprecationWarning)
  37. return super().__init_subclass__(**kwargs)
  38. class _ExtraMeta(type):
  39. def __getattribute__(self, __name: str) -> Any:
  40. # The @deprecated decorator accesses other attributes, so we only emit a warning for the expected ones
  41. if __name in {'allow', 'ignore', 'forbid'}:
  42. warnings.warn(
  43. "`pydantic.config.Extra` is deprecated, use literal values instead (e.g. `extra='allow'`)",
  44. DeprecationWarning,
  45. stacklevel=2,
  46. )
  47. return super().__getattribute__(__name)
  48. @deprecated(
  49. "Extra is deprecated. Use literal values instead (e.g. `extra='allow'`)", category=PydanticDeprecatedSince20
  50. )
  51. class Extra(metaclass=_ExtraMeta):
  52. allow: Literal['allow'] = 'allow'
  53. ignore: Literal['ignore'] = 'ignore'
  54. forbid: Literal['forbid'] = 'forbid'