Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fixes #452 - Adding support for populate_by_name #454

Merged
merged 2 commits into from
Oct 21, 2024

Conversation

hozn
Copy link
Contributor

@hozn hozn commented Oct 21, 2024

Adds support for populate_by_name model config and a handful of tests to validate this functionality.

  • I wasn't 100% sure on whether the preference was to modify existing tests (which, for example, ensure that populate-by-name is not happening), but I opted to create new tests for this code path specifically.
  • I only added tests for env and dotenv. Let me know if more coverage is needed on some of the alternative options.

@hramezani
Copy link
Member

Thanks @hozn

@hramezani hramezani merged commit 93d7b7b into pydantic:main Oct 21, 2024
21 checks passed
@hozn hozn deleted the populate-by-name branch October 22, 2024 12:48
@mcgfeller
Copy link

I wonder if the following is the intended behavior, as it differs from pydantic.BaseSettings in Pydantic 1.x?

If the value is both present in the configuration and the aliased environment variable, it fails with Extra inputs are not permitted. I don't want to allow extra inputs, because that basically omits validations of mis-spelled settings.

pydantic_settings 2.7.0, pydantic 2.10.3

""" Demonstrate problem of value both present in the settings and in the aliased environment variable """
import os
import pydantic
import pydantic_settings

class Settings(pydantic_settings.BaseSettings):

    model_config = pydantic.ConfigDict(populate_by_name=True)
    my_setting: str = pydantic.Field(default='TEST', validation_alias='ENV_VARIABLE')

""" Test that the settings are correctly loaded """

s = Settings()
assert s.my_setting == 'TEST'

s = Settings(my_setting='PROD')
assert s.my_setting == 'PROD'

os.environ['ENV_VARIABLE'] = 'FAIL'
try:
    s = Settings() # uses env variable
    assert s.my_setting == 'FAIL'

    s = Settings(my_setting='PROD')  # Fails in pydantic_settings 2.7.0, pydantic 2.10.3
    assert s.my_setting == 'FAIL'  # Passes using pydantic.BaseSettings in Pydantic 1.x
finally:
    os.environ.pop('ENV_VARIABLE', None)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants