How can I use external variables in Python like 'extern int x;' in C?

Je-Hoon Song picture Je-Hoon Song · Aug 3, 2013 · Viewed 15.6k times · Source

How can I use external variables in Python, like extern int x; in C?

For example,

main1.py:

from myfunc import print_a 

a = 10 
print a    
print_a()

myfunc.py:

def print_a():
    global a   
    print a

Answer

Bakuriu picture Bakuriu · Aug 3, 2013

Simply re-assign the variable in the module:

import myfunc
from myfunc import print_a 

a = 10 

print a

myfunc.a = a

print_a()

Otherwise it is not possible.

Rememeber that python treats modules in a way that is quite different from C. The import in python does not "copy the contents" of the file in that place, but it executes the code in the given file and creates a module object.

The global variable of the module are the module object attributes, which can be modified as I've shown. There is no such notion as "global variable" except for built-ins.


I'd suggest to refactor your code in such a way that you don't have to modify this global variable at all, moving the code that uses myfunc.a from main1 to myfunc. The fact that you need such global variable is already a code smell that there's something wrong with your code and you should try to fix it.


Actually there is a way to affect the "global scope" but it is so hackish that I don't even want to mention it. Trust me: you don't want to use it. If people see your code using such a hack you may be in physical danger.