Guidance on initialization code in a module

M

mrstevegross

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
 
D

Dave Angel

mrstevegross said:
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.
 
D

David Stanek

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?

I think what you are doing is fine. The only thing that I would do
differently is rename 'something' to 'initialize'. That way your
intent is really obvious.
 

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. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,009
Latest member
GidgetGamb

Latest Threads

Top