tskuzzy
tskuzzy

Reputation: 36476

Modifying global variable with same name as local variable

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?

Upvotes: 28

Views: 16134

Answers (3)

vartec
vartec

Reputation: 134691

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.

Upvotes: 44

PenguinCoder
PenguinCoder

Reputation: 4367

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

Upvotes: 2

KurzedMetal
KurzedMetal

Reputation: 12946

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

Upvotes: 1

Related Questions