Dynamically declared shared constant/variable imported twice problem
Peter Otten
__peter__ at web.de
Fri May 1 07:37:39 EDT 2009
Gabriel Rossetti wrote:
> I have three modules A, B, C;
>
> A declares this globally :
>
> UpdateEvent, UPDATE_EVENT_ID = wx.lib.newevent.NewEvent()
>
> Then they import stuff from each other:
>
> - A imports a constant from module B (in "__main__")
> - A imports a class and some constants from module C
> - B imports a constant from module A
> - C imports UPDATE_EVENT_ID from module A
>
> What happens is that since A imports stuff from B which then in turn
> loads something from A, UPDATE_EVENT_ID gets redefined and when A sends
> an event to C, C doesn't do anything since it doesn't have the same
> UPDATE_EVENT_ID. Does anyone have an idea on how to fix this? If it had
> been a statically defined variable then that wouldn't be "bad", but
> since it's dynamic it does pose problems. More globally, how cn I
> prevent this even with static constants? I don't think it's that great
> to redefine the stuff multiple times and I've already had this problem
> in the past with a constant dict.
Imported modules are cached, so this problem shouldn't occur unless you use
A.py as your main script. In this case it will be cached as "__main__", and
if you import it elsewhere a second copy will be executed and cached as "A".
To fix it create a wrapper script that doesn't create any objects that will
be used elsewhere, e. g.
#!/usr/bin/env python
import A
A.main()
assuming the function A.main() contains the code to start your application
and invoke that instead of A.py
Peter
More information about the Python-list
mailing list