209 points · by tgp · 6y ago · 68 comments
- Python application configuration -> https://github.com/edaniszewski/bison
- Configuration with env variables for Python -> https://github.com/hynek/environ_config
- Configuration library for python projects -> https://github.com/willkg/everett
- Strict separation of config from code -> https://github.com/henriquebastos/python-decouple
This is from my personal notes. See also: https://github.com/vinta/awesome-python#configuration
Anything else that we've missed ?
marshmallow.readthedocs.io/en/
One thing missing from this article is to always use a proper external key value store for everything but the stage (dev test prod etc) and the connections to the kv store. Config files on disk and even in environment variables suck for anything but the most trivial platforms.
https://github.com/madman-bob/python-dataclasses-serializati...
Works really well with marshmallow for additional validation.
https://github.com/google/gin-config
and Facebook's Hydra:
What should I finally do? How to put everything together without creating an hard-to-maintain mess of casting/parsing/configuration? Should I manually cast strings to integers (or other types) for all and each value I parse? Where do I keep default values? It's cumbersome to have them embedded in code for get().
I usually want a) a default configuration kept in a file b) a way to override that config with other files, but only for certain parts (I don't want to rewrite the configuration every time), c) a way to override the config at launch time (e.g. from cmdline)
The fact that Python is dynamically typed/type hinted only makes it harder than statically typed languages at configuration, where most configuration libraries instantiate an adequate type conversion function to put a string somewhere.
I ultimately found that the latest solution (parse from json) is good enough for most use cases for points a) and b); since json is typed, a decent conversion can happen for 95% of the use cases (for the others, just use a string and manually parse).
A sidenote to the author if he/she's reading: datetime.date objects, just as python's own naive datetime objects, are dangerous objects that can lead to unpredictable results when used with actual time-handling code. I wouldn't use them anywhere in my Python code.
How much it modifies the software is determined by the software author. If there aren't limits imposed in your example (json) you're still going to get unexpected results. You'll have to limit what's accepted.
Also, what if I allow a config.py file then translate that to .json then back to python? That is no better than just allowing the consumption of a python source file and simply ignoring any disallowed code (again, limiting what is accepted).
I know it's vogue to say configuration as code is bad; that simply has not been my experience.
Python datetime objects, by design, can be naive or timezone-aware. Timezone-aware datetime objects are OK; they identify a certain instant in time.
Naive datetime objects are Python-only abstractions (AFAIK) that don't identify anything in the real world; they're highly error prone, because there's no "right" way to use them.
They sort of work properly only if used in a very limited scope - e.g. your own code only, for small sections - but they're risky because they're not a different type (with respect to tz-aware), and it's hard to tell what any code accepting a datetime does if passed a naive object. Some libraries like java.time DO have a similar concept (e.g. LocalTime, LocalDate) but they keep it well separate from the "real" concept (e.g. Instant or Date in Java) so you can't use them accidentally.
Example: you pass a naive datetime object to any library which must translate it to an instant, like an ISO string with a well defined timezone. What does the library do? Throw an exception? Associate an arbitrary timezone (e.g. UTC)? Associate the local, current timezone? There's no "correct" behaviour.
Transparent timezone awareness always fail, unless you are 100% certain that a tzaware datetime object will remain uncoverted from the very top to the very bottom of the stack and all the way up again no matter who is reading and what they are doing.
For longterm minimization of pain, bugs and effort, you convert datetimes to UTC as early as possible and take them back to some localized version as late as possible (in the frontend, for a webapp, so that the backend never needs to know there is such a thing as timezones (except for separate validation and correction routines, since timezone definitions always end up being incorrect to some degree when you use them at scale)).
If the localization of the datetime is an essential aspect (such as the departure time of a ship leaving port), you store a UTC value together with a record of the location. Only at the latest possible moment of processing, should you do a lookup on the location data to make a local time.
Obviously, there will be exceptions to this rule. If you batch process billions of timestamps under a tight deadline and must do calculations in local time, it might make sense to have the values persisted localized.
Naive datetime is what datetime.utcnow() returns. UTC is essentially a "default" timezone. I've always thought it made most sense in a library to assume it's UTC.
If parameters are defined close to usage, and strongly typed, then it's hard to cleanly search for good configurations of the parameters. Especially for fancier search strategies, you want all parameter lookups to go through a single file.
On the other hand, there's a lot of code churn until an ML pipeline is finished. And errors from typos and type violations will often only show up after hours of training. So it's also painful to try to keep a separate, loosely-typed parameter file in sync.
So far, my compromise is to:
(1) on a first pass, define all parameters as global variables at the top of the files they are used in
(2) once mostly code-complete, pull them into a separate file that tracks initial values, current values, and search ranges. Make all usages go through a lookup where the key is an enum, but the value is untyped:
def param(name: ParamName) -> Any:
return params[name].current_value
Which is not ideal. Does anyone else keep running into this problem and have a better solution?So in place of that I would:
1. Define a variable called Params = Any;
2. Liberally use Param["foo"] and Param["bar"] anywhere.
3. Once you stabilize, reimplement Params as a TypedDict. You'll get failures if accessing any invalid key.
You can also use a NamedTuple if you prefer.
If you insist passing a param name, then you'll have to create a big list of Literals for param with every key in your dict. So Param = Literal["foo", "bar"] etc.
* validate at start (using the type keyword argument for add_argument) * access by name as identifier, not string
And what is more is, that default values are stored with the configuration, plus you add a help text for telling everyone what the argument is for.
One downside is that you command line call gets longer.
https://github.com/kensho-technologies/grift
Handles typing really well, as well as config defaults and fallbacks, giving you the ability to configure your app a few ways, and fall back on other configs if something isn't specified.
That provides typed and validated auto-loading from env vars. I have been quite happy with that in conjunction with an optional .toml file, to do flexible config cleanly and simply like:
import toml
from myproj.conf.types import Settings # a pydantic BaseSettings model
try:
_config = toml.load('myproj.toml')
except FileNotFoundError:
_config = {}
settings = Settings(
**{key.upper(): val for key, val in _config.items()}
)To be clear, I am not suggesting using JSON for config, I think that would be my last choice. My point is that ConfigParser isn't really an alternative to rolling your own if you want decent validation etc (those spec files are horrible to use). You very quickly need to start extending ConfigParser to the point where you've started rolling your own. And at that point you'd be better off with one of the other (tested) solutions already suggested.
When you are ready to move to a more generic solution, your .config or .yml file can generate these.
The advantage here is both flexibility (it's Python) and control (allow/disallow whatever you want).
If you need nested items, use nested classes.
Until you the app reaches the level of advanced yaml config files for cloud deployments, it’s really hard to beat a “config.py” that does a single read of all your ENV_VARS at startup
https://github.com/mixmastamyk/tconf
I'll see if I can add any advice this article gives; feedback would be helpful.