Guidance on initialization code in a module

Dave Angel davea at ieee.org
Wed Jun 17 00:31:44 CEST 2009


mrstevegross wrote:
> Is there a common way to initialize various stuff in a module? That
> is, I have some code in my module that I want to run whenever the
> module is imported. Currently, my module looks like this:
>
> === foo.py ===
> def something():
>   ...
>
> def somethingelse():
>   ...
>
> something()
> === EOF ===
>
> Is the 'something()' line at the end in an ok location? I just put it
> at the end. Maybe there's some special __init__() mechanism for
> modules? Or should I use the 'if __name__ != '__main__'' trick?
>
> Thanks,
> --Steve
>
>   
You're doing fine.  Everything in the module is run when it's imported.  
Running a definition, of course, compiles it, and adds its name to the 
module's namespace.  But anything outside of a definition or class, or 
other qualifier will just be run.

If the module will never be used as a script, the if __name__ == logic 
isn't needed.  If you want this initialization code to be run *only* if 
it's not being run as a script, then you'd do as you suggest, if 
__name__ != "__main__"

But usually, the initialization code wants to be run whether it's being 
used as a script, or as a library module.  So leave the conditional off, 
till you actually decide what behavior should be conditional.





More information about the Python-list mailing list