ets-labs / python-dependency-injector

Dependency injection framework for Python
https://python-dependency-injector.ets-labs.org/
BSD 3-Clause "New" or "Revised" License
3.69k stars 295 forks source link

Object provider raises deprecation warning with pydantic models #773

Open febus982 opened 6 months ago

febus982 commented 6 months ago

Using the object provider to store a pydantic model triggers a deprecation warning.

from dependency_injector.containers import DeclarativeContainer, WiringConfiguration
from dependency_injector.providers import Object, Dependency
from pydantic import BaseModel

class MyObject(BaseModel):
    some_property: str = "some_value"

class MyContainer(DeclarativeContainer):
    wiring_config = WiringConfiguration(
        packages=[
            "gateways",
            "domains",
        ]
    )
    o = Dependency(instance_of=MyObject)

MyContainer(
    o=Object(MyObject()),
)

This is the raised warning

  /path/to/pypoetry/virtualenvs/<virtualenv_name>/lib/python3.11/site-packages/pydantic/_internal/_model_construction.py:248: PydanticDeprecatedSince20: The `__fields__` attribute is deprecated, use `model_fields` instead. Deprecated in Pydantic V2.0 to be removed in V3.0. See Pydantic V2 Migration Guide at https://errors.pydantic.dev/2.5/migration/
    warnings.warn('The `__fields__` attribute is deprecated, use `model_fields` instead.', DeprecationWarning)

I believe the warning is raised during wiring, because removing the WiringConfiguration from the container removes the warning (and, of course, the container wiring)

AlleLouis commented 6 months ago

I found a similar issue: https://github.com/pydantic/pydantic/issues/8153

For now, I used a temporary workaround similar to the one suggested in the comments.

# pyproject.toml
[tool.pytest.ini_options]
filterwarnings = [
    "ignore:The `__fields__`.*deprecated, use `model_fields`.*:DeprecationWarning"
]
febus982 commented 5 months ago

Thanks @AlleLouis for linking the other issue in pydantic repository.

Honestly it doesn't look correct to just suppress the warning because it would just hide the issue.

It would be great to confirm if this fix https://github.com/pydantic/pydantic/pull/8262 will also fix this issue.