home-assistant-libs / pytradfri

IKEA Trådfri/Tradfri API. Control and observe your lights from Python. Examples available. On pypi. Sans-io.

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Issue with pydantic's newly enforced field name check

4ch1m opened this issue · comments

commented

Hi there,

I'm experiencing issues when using the pytradfri library in an app with Gunicorn.

However, the issue seems to be related to pydantic in first place.

I get this error while bootstrapping:

  File "/usr/local/lib/python3.11/site-packages/pydantic/_internal/_model_construction.py", line 171, in __new__
    set_model_fields(cls, bases, config_wrapper, types_namespace)
  File "/usr/local/lib/python3.11/site-packages/pydantic/_internal/_model_construction.py", line 361, in set_model_fields
    fields, class_vars = collect_model_fields(cls, bases, config_wrapper, types_namespace, typevars_map=typevars_map)
                         ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/local/lib/python3.11/site-packages/pydantic/_internal/_fields.py", line 112, in collect_model_fields
    raise NameError(f'Field "{ann_name}" has conflict with protected namespace "{protected_namespace}"')
NameError: Field "model_number" has conflict with protected namespace "model_"

The root cause seems to be this class:

model_number: str = Field(alias=ATTR_DEVICE_MODEL_NUMBER)

Having field names prefixed with model seems to be discouraged now:

All methods on models will start with model_, fields' names will not be allowed to start with "model" (aliases can be used if required).

(see: Model Namespace Cleanup)

Not sure how/if this could/should be fixed in the pytradfri library though.

Thanks for reading. 😄

Pydantic 2.0 has new restrictions on attribute names. You can work around it for now by pinning pydantic to a version < 2.

We'll have to think about how to handle this here in the library.

commented

All right. Thanks for the feedback. 👍

I did an upgrade to 2.0 in another library and apparently, in order to be able to transition smoothly into the new version, you can selectively import from v1 of the library under v2. This is a potential way to move forward and keep the current field name.