Is it possible to write a function which inserts an object into the global namespace and binds it to a variable? E.g.:
>>> 'var' in dir() False >>> def insert_into_global_namespace(): ... var = "an object" ... inject var >>> insert_into_global_namespace() >>> var "an object"
Normally, when you create a variable inside a function, that variable is local, and can only be used inside that function. To create a global variable inside a function, you can use the global keyword.
If you want to refer to a global variable in a function, you can use the global keyword to declare which variables are global.
To access a global variable in a function, if the function has a local variable with the same name, we use the global keyword before the variable name.
The keyword global is used when you need to declare a global variable inside a function. The scope of normal variable declared inside the function is only till the end of the function. However, if you want to use the variable outside of the function as well, use global keyword while declaring the variable.
It is as simple as
globals()['var'] = "an object"
and/or
def insert_into_namespace(name, value, name_space=globals()): name_space[name] = value insert_into_namespace("var", "an object")
Remark that globals
is a built-in keyword, that is, 'globals' in __builtins__.__dict__
evaluates to True
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With