How to initialize a class variable once

Brian Allen Vanderburg II BrianVanderburg2 at aim.com
Tue Dec 9 06:31:12 EST 2008


mccredie at gmail.com wrote:
>
> Unless you are calling reload() on the module, it will only ever get
> _loaded_ once. Each additional import will just yield the existing
> module. Perhaps if you post an example of the behavior that leads you
> to believe that the class variables are getting reinitialized I can
> provide more useful help.
>
> Matt
> --
> http://mail.python.org/mailman/listinfo/python-list
>   

There is one situation where a module can be imported/executed twice, if 
it is the __main__ module.  Obviously the example below would be 
considered bad Python practice but it just shows how it can be done:

main.py:

class Blah(object):
    def action(self):
        print "action"

print "import"

if __name__ == "__main__":
    import app
    app.run()


app.py:

def run():
    import main
    blah = main.Blah()
    blah.action()


python main.py:

import
import
action

The reason is the first time main.py gets loaded, it is known as 
'__main__' but when app imports main, it is not in sys.modules so it 
loads 'main.py' again but this time as 'main'

Brian Vanderburg II


-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20081209/8545b62f/attachment-0001.html>


More information about the Python-list mailing list