Skip to content

Instantly share code, notes, and snippets.

@daaniam
Last active April 17, 2023 04:05
Show Gist options
  • Save daaniam/42b0284191f3c908b41cc9d2f31f1e45 to your computer and use it in GitHub Desktop.
Save daaniam/42b0284191f3c908b41cc9d2f31f1e45 to your computer and use it in GitHub Desktop.
Pydantic set env_prefix

Add (set_prefix) method to your settings class...

class MyConfig(BaseSettings):
    logging_level: str = "example"

    @classmethod
    def set_prefix(cls, prefix: str):
        cls.__config__.env_prefix = prefix
        for field in cls.__fields__.values():
            cls.__config__.prepare_field(field)

    class Config:
        env_file = '.env'
        env_file_encoding = 'utf-8'

set prefix before class init

MyConfig.set_prefix("MY_PREFIX_")
conf = MyConfig()

or as a method....whatever

def init_config() -> MyConfig:
    conf = MyConfig
    conf.set_prefix(self.meta.prefix + "_")
    return conf()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment