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?
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.
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.
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).
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.
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.
>>> a = 'foo' >>> def my_func(a='bar'): ... return globals()['a'] ... >>> my_func() 'foo'
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