BaseSettings Singleton option?
See original GitHub issueI’ve noticed a pattern come up in several of our projects and thought maybe (but I’m really not sure) pydantic could ship support for it.
# config.py
from functools import lru_cache
from pydantic import BaseSettings
class Config(BaseSettings):
a: str
b: str
c: str
@lru_cache()
def read() -> Config:
return Config()
# a.py
from . import config
conf = config.read
# b.py
from . import config
conf = config.read
Would it be a good library addition if we could do something like:
# config.py
from functools import lru_cache
from pydantic import BaseSettings
class Config(BaseSettings):
a: str
b: str
c: str
class Config:
singleton = True
# a.py
from . import Config
conf = Config()
# b.py
from . import config
conf = Config()
I definitely appreciate that pydantic should not try to take care of application-level features like dependency injection and object caching. However, for the special case of BaseSettings this just seems like a practical feature. Thoughts?
Maybe there is already a more general solution here that is readily available that i missed, allowing e.g.:
# config.py
from pydantic import BaseSettings
@singleton # exists?
class Config(BaseSettings):
a: str
b: str
c: str
But I haven’t come across that yet. And if such a thing is from another third party lib. I still feel then that there is value in pydantic shipping an out of box solution, if its what users would want most of the time.
Issue Analytics
- State:
- Created 4 years ago
- Reactions:4
- Comments:6 (1 by maintainers)
Top Related StackOverflow Question
I completely agree
settingsshould be a singleton, however I’ve never had any problem creating it as a singleton which is then used throughout the application.This is probably because most applications I build are either based on aiohttp or use aiohttp’s approach of a single “app” context.
See for example here. This approach also works well for testing where you generally want a very different settings instance which can easily be changed on a per-test basis without reloading modules.
My suspicion is that you’ve made design mistakes if you find yourself trying to initialise settings more than once. Probably best you fix the root mistake or take care of the workaround outside pydantic.
I usually put these in a factory function with lru_cache