Importing modules from miscellaneous folders

Benjamin Kaplan benjamin.kaplan at case.edu
Wed Jan 5 22:48:08 EST 2011


On Wed, Jan 5, 2011 at 8:08 PM, Jshgwave <jshgwave at yahoo.com> wrote:
>
> On a Windows PC, I would like to be able to store modules in
> topic-specific foldersinstead of in Python26/Lib/site-packages,
> and then import into an IPython session those modules and the
> functions in them.
>
> To test this, I have made a toy module:
>
> ---
>
> """
>  toy_module.py
>
>  This is for testing the importing of modules from folders
>  other than "Lib".
>
>  The first statement below is from Langtangen, Primer, p.143.
>  At allows running the module as a program, as well as
>  importing it as a module.
> """
>



>
> if __name__ == '__main__' :
>


You've misunderstood what this statement does. Any python script can
be executed as a program. In fact, all Python modules are scripts.
Upon running or importing them, they are executed. Anything at the top
level is run.

If a module is imported, it's __name__ attribute will be the name of
the script. If the module is run as a script, it's __name__ will be
"__main__". By checking to see if the __name__ == "__main__", you can
have certain code only run if the script is run as a program, as
opposed to being imported as a module.

The def statement in python is an executable statement, not a
declaration. The function does not exist until after the def statement
is executed. Because your functions are only created if __name__ ==
"__main__", they don't exist when __name__ == "toy_module", which is
the case when you import it in the ipython shell. That's what's
causing your error.



More information about the Python-list mailing list