Reducing duplicate variable name when using os.getenv

I often find that I am writing code of recurring feelings in the style below (how this happens inside Django settings.py, but the question is implied much more broadly):

STACKEXCHANGE_CLIENT_ID = os.getenv('STACKEXCHANGE_CLIENT_ID')
STACKEXCHANGE_CLIENT_SECRET = os.getenv('STACKEXCHANGE_CLIENT_SECRET')
# et cetera

Naturally, there are many cases where I do not want the name of my local variable to match the name of the environment variable, but this happens enough that I wonder if there is a good way to avoid duplicate names.

The following code works for me:

_locals = locals()
def f(x):
    _locals[x] = os.getenv(x)

f('TERM')

print TERM

but I am not going to use this in the production process, since, quoting the Python documentation fromlocals() :

Note: The contents of this dictionary should not be changed;

, "" / "" , , ?

+3
2

: () ?

import sys, os

opts = (
    'STACKEXCHANGE_CLIENT_ID', 
    'STACKEXCHANGE_CLIENT_SECRET'
)

module = sys.modules[__name__]
for o in opts:
    setattr(module, o, os.getenv(o))

, , globals() ...

_g = globals()
for o in opts:
    _g[o] = os.getenv(o)
+4

, , , :

STACKEXCHANGE_CLIENT_ID = os.getenv('STACKEXCHANGE_CLIENT_ID')
STACKEXCHANGE_CLIENT_SECRET = os.getenv('STACKEXCHANGE_CLIENT_SECRET')

:

envars['STACKEXCHANGE_CLIENT_ID'] = os.getenv('STACKEXCHANGE_CLIENT_ID')
envars['STACKEXCHANGE_CLIENT_SECRET'] = os.getenv('STACKEXCHANGE_CLIENT_SECRET')

os.environ.

0

All Articles