[Tutor] modules == class instances?

Danny Yoo dyoo@hkn.eecs.berkeley.edu
Tue, 2 Apr 2002 19:12:37 -0800 (PST)


On Tue, 2 Apr 2002, Sean 'Shaleh' Perry wrote:

>
> On 03-Apr-2002 Erik Price wrote:
> > I have noticed something in the past day or so -- that the syntax for
> > referring to a module's namespace is identical to the syntax used for
> > referring to a class instance's methods -- you specify the name of the
> > module or the class instance, then a dot, and then you specify the name
> > of the function or property or method you wish to access.
> >
> > When I import a module into a script, does the import process in fact
> > create an object instance to represent the module, or is this just a
> > coincidence?
>
> modules certainly ACT like objects:
>
> >>> import re
> >>> type(re)
> <type 'module'>
> >>> print re
> <module 're' from '/usr/lib/python2.1/re.pyc'>
> >>> dir(re)
> ['DOTALL', 'I', 'IGNORECASE', 'L', 'LOCALE', 'M', 'MULTILINE', 'S', 'U',
> 'UNICODE', 'VERBOSE', 'X', '__all__', '__builtins__', '__doc__', '__file__',
> '__name__', 'compile', 'engine', 'error', 'escape', 'findall', 'match',
> 'purge', 'search', 'split', 'sub', 'subn', 'template']
>
> but I am unsure how python treats them internally.

Yes, modules are also "objects" in Python.  They don't support too many
things besides allowing us to get and set attributes within them, but they
are objects that can be tossed around quite easily and uniformly.

###
>>> import re, string, urllib
>>> for module in [re, string, urllib]:
...     print "Hey, I have a module: ", module
...
Hey, I have a module:  <module 're' from
'/opt/Python-2.1.1/lib/python2.1/re.pyc'>
Hey, I have a module:  <module 'string' from
'/opt/Python-2.1.1/lib/python2.1/string.pyc'>
Hey, I have a module:  <module 'urllib' from
'/opt/Python-2.1.1/lib/python2.1/urllib.pyc'>
###


(If you're a C junkie, you can look at the Python source code, in the
"Objects/moduleobject.c" directory, and you'll see how they're
implemented as objects.)


Hope this helps!