python calling python

David Bolen db3l at fitlinxx.com
Tue Aug 22 18:10:47 EDT 2000


"Larry Whitley" <ldw at us.ibm.com> writes:

>(...)
> main() # to get main called
> 
> # end of file ---------------------------
> 
> Anything else in the above considered harmful in Python?

Nope - just that call to main() without any protection from only
running if the script is your top level script :-)

You have to remember that when you execute (from the command line)
_or_ import a module, Python is actually executing the entire module -
the only real difference is the namespace within which that execution
is taking place.

The "execution" includes your class and function definitions, which
"execute" by being compiled and then the resulting function or class
object being assigned to the label that you gave the class or
function.  In that respect, a "def func(): pass" is akin to a global
assignment statement such as like "func = object" where object is the
resulting compilation of the function body.

That's what leads to the Python idiom that you'll find at the bottom
of most scripts as has been referenced elsewhere in this thread:

    if __name__ == "__main__":
	... do-stuff ...

where do-stuff is what you want to do if the script is the top level
script being run by the interpreter (in which case the namespace is
named "__main__").  This makes it very clean to separate out what
should be done by this script if it is executed directly, while still
supporting the import of the module from another script to be used as
supporting functionality.

It's actually quite elegant.  For me, it first hit home after first
having completed a script that I fully intended to be standalone, and
to be honest hadn't completely designed for others to use - in my rush
I had even "gasp" overused some global variables.

But then, as things are wont to happen, one of its top-level functions
(not even a class) turned out to be really handy for something else I
needed to do.  So I just imported the script as a module in another
script and called the function.  The fact that Python scoped my
original script as a module, and that the functions (and global names)
simply became exported as "methods" of that module - without any
pollution of my new scripts namespace - was just amazingly clean and
painless!

--
-- David
-- 
/-----------------------------------------------------------------------\
 \               David Bolen            \   E-mail: db3l at fitlinxx.com  /
  |             FitLinxx, Inc.            \  Phone: (203) 708-5192    |
 /  860 Canal Street, Stamford, CT  06902   \  Fax: (203) 316-5150     \
\-----------------------------------------------------------------------/



More information about the Python-list mailing list