Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Modifying global variable with same name as local variable

Tags:

Suppose I have a global variable a. And within a function definition, we also have a local variable named a. Is there any way to assign the value of the global variable to that of the local variable?

a = 'foo'  def my_func(a = 'bar'):     # how to set global a to value of the local a? 
like image 667
tskuzzy Avatar asked Apr 19 '12 20:04

tskuzzy


People also ask

What happens if the local and global variable has the same name?

If a global and a local variable with the same name are in scope, which means accessible, at the same time, your code can access only the local variable.

Can a local variable have the same name as a global variable?

A program can have the same name for local and global variables but the value of a local variable inside a function will take preference. For accessing the global variable with same rame, you'll have to use the scope resolution operator.

Can a function have a local variable with the same name as that of a global variable in the script?

Yes; before the local declaration. Better yet, don't use globals but pass the values as parameters. If you don't use globals it means your function code can be used in other scripts (encapsulated).

How do you access a global variable with the same name?

Global Variable: The variable that exists outside of all functions. It is the variable that is visible from all other scopes. We can access global variable if there is a local variable with same name in C and C++ through Extern and Scope resolution operator respectively.


2 Answers

Use built-in function globals().

globals()

Return a dictionary representing the current global symbol table. This is always the dictionary of the current module (inside a function or method, this is the module where it is defined, not the module from which it is called).

a = 'foo'  def my_func(a = 'bar'):     globals()['a'] = a 

BTW, it's worth mentioning that a global is only "global" within the scope of a module.

like image 74
vartec Avatar answered Sep 17 '22 17:09

vartec


>>> a = 'foo' >>> def my_func(a='bar'): ...     return globals()['a'] ... >>> my_func() 'foo' 
like image 26
KurzedMetal Avatar answered Sep 21 '22 17:09

KurzedMetal