Odd behaviour on importing variable from module

rs387 rstarkov at gmail.com
Sat Aug 23 08:05:02 EDT 2008


Hi,

I've found the following behaviour on importing a variable from a
module somewhat odd. The behaviour is identical in Python 2.5 and
3.0b2.

In summary, here's what happens. I have a module, oddmodule.py
(below), that defines a variable, OddVariable, by assigning a value A
to it. The file I execute, mainfile.py, imports and re-binds
OddVariable to a value B. I have two test modules which import the
OddVariable in two different ways, one via "import oddmodule" and
another via "from oddmodule import OddVariable".

The weird behaviour is that by importing using the former syntax, I
can see OddVariable bound to B (as expected), but the latter syntax
sees it bound A.

Is this the intended behaviour? Am I misunderstanding what is going on
here?


Source code:

<<<oddmodule.py>>>

print("Importing oddmodule")
OddVariable = ["not", "initialized"]

def OddFunction():
    print("    OddVariable from oddmodule.OddFunction:", OddVariable)


<<<mainfile.py>>>

import oddmodule
import testmodule1
import testmodule2

print("Initializing OddVariable")

oddmodule.OddVariable = ["some", "list"]

print()
testmodule2.DoTest()
print()
testmodule1.DoTest()


<<<testmodule1.py>>>

from oddmodule import OddVariable, OddFunction

def DoTest():
    print("STARTING testmodule1.DoTest")
    print("    OddVariable from testmodule1:", OddVariable)
    OddFunction()
    print("FINISHED testmodule1.DoTest")


<<<testmodule2.py>>>

import oddmodule

def DoTest():
    print("STARTING testmodule2.DoTest")
    print("    OddVariable from testmodule2:", oddmodule.OddVariable)
    oddmodule.OddFunction()
    print("FINISHED testmodule2.DoTest")



OUTPUT:

Importing oddmodule
Initializing OddVariable

STARTING testmodule2.DoTest
    OddVariable from testmodule2: ['some', 'list']
    OddVariable from oddmodule.OddFunction: ['some', 'list']
FINISHED testmodule2.DoTest

STARTING testmodule1.DoTest
    OddVariable from testmodule1: ['not', 'initialized']      !!! OLD
VALUE !!!
    OddVariable from oddmodule.OddFunction: ['some', 'list']
FINISHED testmodule1.DoTest


Many thanks,

Roman



More information about the Python-list mailing list