code in a module is executed twice (cyclic import problems) ?

Stephen Fairchild somebody at somewhere.com
Sun Oct 11 12:50:33 EDT 2009


ryles wrote:

>> I always thought code in a module was only executed once,
>> but doesn't seem to be true.
>>
>> I'm using Python 2.5.
>>
>> And this is the example:
>>
>> == A.py ==
>> My_List = []
>>
>> == B.py ==
>> from A import *
>> My_List.append ( 3 )
>> print 'B', My_List
>> import C
>>
>> == C.py ==
>> from A import *
>> from B import *
>> print 'C', My_List
>>
>> Now when you start with B.py as the main program,
>> this is the resulting output:
>>
>> B [3]
>> B [3, 3]
>> C [3, 3]
>>
>> Why is the B.py executed twice ?

B.py is the entry point of the program and it is known internally as
__main__. There is no record of a B.py.

If you really must import objects from the main module you can do it like
this.

from __main__ import *
-- 
Stephen Fairchild



More information about the Python-list mailing list