Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Insert variable into global namespace from within a function? [duplicate]

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" 
like image 579
Dan Avatar asked Aug 05 '12 01:08

Dan


People also ask

Can we assign a value to global variable within a function?

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.

How do you make a function variable refer to the global variable?

If you want to refer to a global variable in a function, you can use the global keyword to declare which variables are global.

How can you access a global variable inside the function if function has a variable with same name?

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.

How do you declare a global variable inside a function in Python?

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.


1 Answers

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.

like image 92
jolvi Avatar answered Sep 21 '22 12:09

jolvi