Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Imports in python are static, any solution?

Tags:

python

foo.py :

i = 10

def fi():
    global i
    i = 99

bar.py :

import foo
from foo import i

print i, foo.i
foo.fi()
print i, foo.i

This is problematic. Why does i not change when foo.i changes?

like image 981
Xolve Avatar asked Dec 02 '22 08:12

Xolve


1 Answers

What Ross is saying is to restucture foo like so:

_i = 10

def getI():
    return _i

def fi():
    global _i
    _i = 99

Then you will see it works the way you want:

>>> import foo
>>> print foo.getI()
10
>>> foo.fi()
>>> print foo.getI()
99

It is also 'better' in the sense that you avoid exporting a global, but still provide read access to it.

like image 181
Shane C. Mason Avatar answered Dec 14 '22 13:12

Shane C. Mason