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?
Let python know that you want the global version;
Use built-in function
globals()
.BTW, it's worth mentioning that a global is only "global" within the scope of a module.
Don't muddle global and local namespaces to begin with. Always try and use a local variable versus a global one when possible. If you must share variables between scopes you can still pass the variables without need for a global placeholder. Local variables are also referenced much more efficiently accessed than globals.
A few links:
Sharing Variables in Python
Variable performance