Dynamically declared shared constant/variable imported twice problem

Discussion in 'Python' started by Gabriel Rossetti, May 1, 2009.

  1. Hello everyone,

    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.

    Thank you,
    Gabriel Rossetti, May 1, 2009
    1. Advertisements

  2. Gabriel Rossetti

    Peter Otten Guest

    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

    assuming the function A.main() contains the code to start your application
    and invoke that instead of A.py

    Peter Otten, May 1, 2009
    1. Advertisements

  3. Thank you Peter, I understand better now. I am indeed using A.py as my
    main script. I will create a launcher then, thank you.

    Gabriel Rossetti, May 1, 2009
    1. Advertisements

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments (here). After that, you can post your question and our members will help you out.