Search code examples
pythonnamespacesglobal-variables

Insert variable into global namespace from within a function?


Is it possible to add an object to the global namespace, for example, by using globals() or dir()?

def insert_into_global_namespace(var_name, value):
    globals()[var_name] = value


insert_into_global_namespace('my_obj', 'an object')
print(f'my_obj = {my_obj}')

But this only works in the current module.


Solution

  • Yes, just use the global statement.

    def func():
        global var
        var = "stuff"