22
votes

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?
4
use 'global a' statement within the function definition? - newtover
@newtover: But then I can't access the value of the local a in order to assign it to the global one. - tskuzzy
WHY???!!1!11one|11!1ELEVE|\|1!?. To start, using globals is a bad practice, add a parameter to your func or make a class. Second, why would you want to use the same variable name in different contexts and relate their content. Can you try harder in making your code more ugly and confusing? - KurzedMetal
This is exactly why using global variables is discouraged. Even if there is a way to do this, you shouldn't do it. Change the local variable name, or -- better yet -- don't use a global variable. - senderle
A bit late to the party, but whenever I hit the local/global collision issue, I use an empty class as a namespace container (class Container(): pass, settings = Container(), settings.a = 'foo') and store my global variables in there. It's both mutable and distinguishable: if var1 is None: var1 = settings.var1, else: settings.var1 = var1 and so on. - Nisan.H

4 Answers

36
votes

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.

1
votes

Let python know that you want the global version;

def my_func():
    global a
    a = 'bar'
1
votes

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

0
votes
>>> a = 'foo'
>>> def my_func(a='bar'):
...     return globals()['a']
...
>>> my_func()
'foo'