-
-
Notifications
You must be signed in to change notification settings - Fork 104
Closed as duplicate of#536
Labels
Description
When declaring a type alias, any JSON inside an env var will stop being parsed. Consider the following code (run with uv run reproduction.py
):
# /// script
# requires-python = ">=3.12"
# dependencies = [
# "pydantic-settings",
# ]
# ///
import os
from pydantic_settings import BaseSettings
type MyType = list[int]
print(MyType, type(MyType)) # prints "MyType <class 'typing.TypeAliasType'>"
class Settings(BaseSettings):
MY_VAR: MyType
os.environ["MY_VAR"] = "[1, 2, 3]"
settings = Settings() # type: ignore
print(settings.MY_VAR, type(settings.MY_VAR))
This fails with an error message:
Traceback (most recent call last):
File "reproduction.py", line 21, in <module>
settings = Settings() # type: ignore
^^^^^^^^^^
File ".../site-packages/pydantic_settings/main.py", line 188, in __init__
super().__init__(
File ".../site-packages/pydantic/main.py", line 253, in __init__
validated_self = self.__pydantic_validator__.validate_python(data, self_instance=self)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
pydantic_core._pydantic_core.ValidationError: 1 validation error for Settings
MY_VAR
Input should be a valid list [type=list_type, input_value='[1, 2, 3]', input_type=str]
For further information visit https://errors.pydantic.dev/2.11/v/list_type
It works fine if the type is not an alias. When replacing like this, there's no error:
-type MyType = list[int]
+MyType = list[int]
Instead, the output looks as expected:
list[int] <class 'types.GenericAlias'> # output of print(MyType, type(MyType))
[1, 2, 3] <class 'list'> # output of print(settings.MY_VAR, type(settings.MY_VAR))
This just took me a bit to figure out. I'd expect a type alias not to change any behavior of the parsing.