Skip to content

Instantly share code, notes, and snippets.

@apowers313
Last active January 22, 2025 05:35
Show Gist options
  • Save apowers313/f455cde79b99cd5f4568a98885290231 to your computer and use it in GitHub Desktop.
Save apowers313/f455cde79b99cd5f4568a98885290231 to your computer and use it in GitHub Desktop.
Reproduction of a Pydantic Setting bug where environment variables don't parse variables without prefixes
import os
from pydantic import BaseModel, ValidationError
from pydantic_settings import BaseSettings, SettingsConfigDict
class Config(BaseSettings):
model_config = SettingsConfigDict(env_prefix='my_prefix_', env_file=".env", extra="forbid")
foo: list[str]
try:
os.remove(".env")
except Exception:
pass
# first: try parsing a list from an environment variable with a prefix
list_value = '["testy"]'
os.environ['my_prefix_foo'] = '["testy"]'
print("First Config", Config())
print("is list", isinstance(Config().foo, list))
# output:
# First Config foo=['testy']
# is list True
del os.environ['my_prefix_foo']
print("\n")
# second: try parsing a list from an environment variable with a prefix
list_value = '["testy"]'
os.environ['foo'] = '["testy"]'
try:
Config()
except ValidationError as e:
print("Second Config:", e)
# output:
# Second Config: 1 validation error for Config
# foo
# Input should be a valid list [type=list_type, input_value='["testy"]', input_type=str]
# For further information visit https://errors.pydantic.dev/2.10/v/list_type
del os.environ['foo']
print("\n")
# third: try parsing a list from a .env variable with a prefix
with open(".env", "w") as file:
file.write(f"my_prefix_foo={list_value}")
print("Third Config", Config())
print("is list", isinstance(Config().foo, list))
# output
# Third Config foo=['testy']
# is list True
os.remove(".env")
print("\n")
# fourth: try parsing a list from a .env variable WITHOUT a prefix
with open(".env", "w") as file:
file.write(f"foo={list_value}")
try:
Config()
except ValidationError as e:
print("Fourth Config:", e)
# Fourth Config: 1 validation error for Config
# foo
# Input should be a valid list [type=list_type, input_value='["testy"]', input_type=str]
# For further information visit https://errors.pydantic.dev/2.10/v/list_type
os.remove(".env")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment