import sys
thismodule = sys.modules[__name__]
setattr(thismodule, name, value)
or, without using setattr
(which breaks the letter of the question but satisfies the same practical purposes;-):
globals()[name] = value
Note: at module scope, the latter is equivalent to:
vars()[name] = value
which is a bit more concise, but doesn’t work from within a function (vars()
gives the variables of the scope it’s called at: the module’s variables when called at global scope, and then it’s OK to use it R/W, but the function’s variables when called in a function, and then it must be treated as R/O — the Python online docs can be a bit confusing about this specific distinction).