I have a problem with my program and I was able to reproduce this unexpected (at least unexpected to me) behavior in a small scale so now I’m certain it is not another bug.
Lets say I have 3 python modules: one, two and three.
In three we have:
var = 0
list = []
So there we have a integer that is equal to zero and and empty list.
In two we have:
from three import var, list
def funct():
print var*2
print list
return
So we import var and list and simply define a function that will print both and return.
Instead of calling funct() in two I called it in one, but not before doing some “operations” to them.
from three import var, list
from two import funct
if 2 < 4:
var += 1
list.append("x")
print funct()
So here comes my question.
I never expected this result:
0
['x']
None
How come the x was added to the list with the append() and 1 was NOT added to var, to be clear. I was expecting:
2
['x']
None
If find it very strange that they receive different treatments under the same circumstances.
- Am I missing something here?
- Am I doing something wrong with the imports?
If not:
- Why does it behave like this?
- How should this problem be solved / approached?
Thank in advance.
To “fix” your program, you would have to add “global var”, as in:
But this is illegal according to http://docs.python.org/reference/simple_stmts.html#global:
Then again, following the link above:
Edit:
The solution is to change:
to:
then don’t use global namespace, but specify explicitly the namespace of three (you imported the symbol)
code:
Make sure two.py and one.py are changed accordingly in their import/from statements
http://docs.python.org/tutorial/modules.html#more-on-modules