1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More.
  2. Anuncie Aqui
    Anuncie aqui você Também: fdantas@4each.com.br

[Python] Is it possible to set the type of a field based on the value of another field?

Discussão em 'Python' iniciado por Stack, Setembro 15, 2025.

  1. Stack

    Stack Membro Participativo

    I want to set and instantiate the right type based on the value of another field and get typing and autocomplete on it.

    I want this to happen automatically when the class is instantiated:

    TMyBackendConfig = TypeVar("TMyBackendConfig")

    class MyBackendOneConfig(BaseSettings):
    field_one: str = "1111111"

    class MyBackendTwoConfig(BaseSettings):
    field_two: str = "222222222"

    class Config(BaseSettings, Generic[TMyBackendConfig]):
    # backend_type: Literal["one", "two"] # want to use this to set right one
    backend_config: TMyBackendConfig

    def test():
    _one = MyBackendOneConfig()
    _two = MyBackendTwoConfig()

    one = Config(backend_config=_one)
    two = Config(backend_config=_one)

    # I get autocomplete and typing
    one.backend_config.field_one
    one.backend_config.field_two


    I want to be able to just do Config(backend_type="one") and get back the object with the right nested config.

    Continue reading...

Compartilhe esta Página