module data member?

Diez B. Roggisch deets at nospam.web.de
Tue Nov 13 12:22:40 EST 2007


Peter J. Bismuti wrote:

> How do you define a "module data member" (I want to understand out how
> this works before making converting to a Class)?
> 
> Right now I'm defining variables in a module that get put into the global
> namespace.  Instead I want to put them in a "module global" namespace that
> will be the same regardless of whether not this module is imported or run
> as __main__.

There is no "real" global namespace, unless you count __builtins__ - which
you shouldn't :)

All your defined top-level (global) module vars are local to that module.

BUT there is of course one tiny probleme here, that arises when using a
module as main script: then the module will be known under two distinct
names, module-name & __main__. The former of course only if someone imports
the module itself.

The common remedy for this is this:


... # lots of code of module myself

def main():
    # do mainy stuff here

if __name__ == "__main__":
   import myself
   myself.main()

This of course won't prevent __main__ to be existant, nor running possible
initialization code twice. But if the module is supposed to do some work,
it will operate on the one data all the other importing modules see.

You can take this one step further, using an explicit init()-function that
creates global state (remember, it's only module-global).

Diez



More information about the Python-list mailing list