-
-
Notifications
You must be signed in to change notification settings - Fork 50
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
Extra inputs are not permitted with AliasChoices #148
Comments
Thanks @levsh for reporting this issue 🙏 By default |
@hramezani thank you for reply. |
Its intended behavior in from pydantic import AliasChoices, BaseModel, ConfigDict, Field
class Settings(BaseModel):
model_config = ConfigDict(extra='forbid', populate_by_name=True)
field: str = Field(alias=AliasChoices("field", "my_field"))
Settings(my_field='foo', field='bar')
"""
pydantic_core._pydantic_core.ValidationError: 1 validation error for Settings
my_field
Extra inputs are not permitted [type=extra_forbidden, input_value='foo', input_type=str]
For further information visit https://errors.pydantic.dev/2.2/v/extra_forbidden
""" |
I migrate my application from Pydantic v1 to v2. My current code is class Settings(BaseSettings):
field: str = Field(env="my_field")
class Config:
extra="forbid" so i can instantiate my service Settings from env variable settings = Settings() or do it explicit settings = Settings(field="abc") Unfortunately, according to docs Thanks for the clarifications |
Why you don't use alias instead of env:
|
@hramezani with import os
from typing import Optional
from unittest import mock
from pydantic import AliasChoices, Field
from pydantic_settings import BaseSettings
def test_settings():
class Settings(BaseSettings):
field: str = Field(alias="my_field")
# 1
env = {}
with mock.patch.dict(os.environ, env, clear=True):
assert Settings(field="bar").field == "bar" # 1
# 2
env = {"my_field": "foo"}
with mock.patch.dict(os.environ, env, clear=True):
assert Settings().field == "foo" # 2
# 3
env = {"my_field": "foo"}
with mock.patch.dict(os.environ, env, clear=True):
assert Settings(field="bar").field == "bar" # 3
test_settings() Exception
|
Hi!
Example code to reproduce:
Third case raises
Expect environment variable 'my_field' to be ignored in favor of explicitly passed field='bar'.
Selected Assignee: @samuelcolvin
The text was updated successfully, but these errors were encountered: