Insert variable into global namespace from within a function?

Viewed 27593

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.

5 Answers

A more terse version of Roland Puntaier's answer is:

import builtins

def insert_into_global_namespace():
    builtins.var = 'an object'
Related