Dan Dan - 1 year ago 64
Python Question

Insert variable into global namespace from within a function?

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()
>>> def insert_into_global_namespace():
... var = "an object"
... inject var
>>> insert_into_global_namespace()
>>> var
"an object"

Answer Source

Yes, just use the global statement.

def func():
    global var
    var = "stuff"
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download