I'm frequently finding myself writing repetitive-feeling code in the style below (as it happens, inside a Django settings.py
, but the question is meant much more generally):
STACKEXCHANGE_CLIENT_ID = os.getenv('STACKEXCHANGE_CLIENT_ID')
STACKEXCHANGE_CLIENT_SECRET = os.getenv('STACKEXCHANGE_CLIENT_SECRET')
# et cetera
Naturally there are plenty of occasions where I don't want my local variable name to match the name of the environment variable, but it's happening enough that I'm wondering if there's a nice way to avoid the name duplication.
The below code works for me:
_locals = locals()
def f(x):
_locals[x] = os.getenv(x)
f('TERM')
print TERM
but I have no intention of using this in production, as, to quote the Python documentation on locals()
:
Note: The contents of this dictionary should not be modified;
so I'm wondering if there exists a valid "supported"/"approved" solution, and if so, what it might look like?