pydantic / pydantic-settings

Settings management using pydantic
https://docs.pydantic.dev/latest/usage/pydantic_settings/
MIT License
508 stars 50 forks source link

env source: superflous deep env conflicts with non-dict model #275

Closed diefans closed 2 months ago

diefans commented 2 months ago

If you define a nested model with a leaf annotated as a string and have deeper nesting environment variables in place, an exception is raised:

class NestedSettings(BaseModel):
    foo: str

class Settings(BaseSettings):
    model_config = SettingsConfigDict(env_nested_delimiter='__')

    nested: NestedSettings
export nested__foo=string
export nested__foo__bar=conflicts_with_string

Exception:

Traceback (most recent call last):
  File "/home/olli/code/bm/pydantic-settings/tests/foo.py", line 40, in <module>
    s = Settings()
        ^^^^^^^^^^
  File "/home/olli/code/bm/pydantic-settings/pydantic_settings/main.py", line 108, in __init__
    **__pydantic_self__._settings_build_values(
      ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/home/olli/code/bm/pydantic-settings/pydantic_settings/main.py", line 215, in _settings_build_values
    return deep_update(*reversed([source() for source in sources]))
                                  ^^^^^^^^
  File "/home/olli/code/bm/pydantic-settings/pydantic_settings/sources.py", line 326, in __call__
    field_value = self.prepare_field_value(field_name, field, field_value, value_is_complex)
                  ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/home/olli/code/bm/pydantic-settings/pydantic_settings/sources.py", line 517, in prepare_field_value
    env_val_built = self.explode_env_vars(field_name, field, self.env_vars)
                    ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/home/olli/code/bm/pydantic-settings/pydantic_settings/sources.py", line 641, in explode_env_vars
    env_var[last_key] = env_val
    ~~~~~~~^^^^^^^^^^
TypeError: 'str' object does not support item assignment