modules
Jim Dennis
jimd at vega.starshine.org
Sun Apr 7 16:14:42 EDT 2002
In article <d9ea2696.0204061049.551bd53b at posting.google.com>, distrex wrote:
>I understand most of python. But I still don't get modules. I know
>they are just basicaly a function but i don't know how to use them
>effectively and what each one does. Everything good in python you will
>at some point need to use a module right. If anyone can help me with
>this i'd be greatful. Info or websites would be nice.
Modules are things that you import into your namespace. The
process of import them (or import *from* them) executes any
code in them. Usually (almost always) a module will only contain
class and function definitions, perhaps some "members" (variables)
and an "if __name__ == '__main__':" suite.
You can think of a module as a library of classes, functions and
variables. As such, it would be inappropriate to create modules
that executed "visible" statements (such as printing stuff) or made
other modifications to the importer's state. Basically modules
should normally just execute whatever is necessary to define their
namespace --- which usually requires NO "execution" (in the traditional
sense) at all. (The confusion is that python is a dynamic language,
so things like:
def foo(): pass
# and
class Bar: pass
... are actually executable statements in Python, where they are
"definitions" or "declarations" in other languages.
The most important thing to realize about Python modules is that they
are singletons. They are only executed upon initial import for any given
interpreter session. Additional imports are not an error, and won't
raise an exception, but they will not re-execute the module's code.
That can be confusing because subsequent import statements can
change change namespaces around. I can do something like:
import bisect as bifoo
from bisect import insort
import bisect
... and I've only execute the contents of bisect once, but I've
made subsequent changes to my namespace (making the bisect.insort()
available directly available without any qualifiers (in my globals()
dictionary). and making it accessible via the bifoo and bisect
namespaces (which is silly, and used just for an example).
You might be aware that there are three sorts of modules in
Python. There are binaries (compiled code, usually from C sources)
which appear as .so (shared object) files under Linux and UNIX, and
.DLL files under MS Windows (don't know for Macs). There are Python
files (simple .py files in python) and there are packages which
are directories that contain __init__.py files with assignments to
__all__ lists. You don't have to know or care about these differences
among these when using the modules. You just use import the same way
regardless of the underlying implementation details.
While *writing* your own modules you can start a module as a .py
and later refactor it into a package or rewrite it in C and compile
as your needs require.
More information about the Python-list
mailing list