[Tutor] file i.o

Danny Yoo dyoo at hkn.eecs.berkeley.edu
Sun Jan 25 16:15:37 EST 2004

On Sun, 25 Jan 2004, [ISO-8859-1] "J=F6rg W=F6lke" wrote:

> > > matching module functions. the module.function() syntax could get
> > > a bit tedious, or is that part of the python way?
> > Actually, it is. But if you want to save yourself some typing, you can


I wouldn't call it tedium.  Even in Perl, you want to avoid doing an
uncontrolled import like that.  In fact, the Perl module documentation at:



Do not export method names!

Do not export anything else by default without a good reason!

Exports pollute the namespace of the module user. If you must export try
to use @EXPORT_OK in preference to @EXPORT and avoid short or common
symbol names to reduce the risk of name clashes.

Sound familiar?

It's the exact same issue in Python.  The cosmetic difference here is that
the Perl folks define @EXPORT/@EXPORT_OK arrays, and the Python folks use
the 'from module import */import' statements.  The majority of the Perl
folks handle namespace pollution just like the Python folks in saying:
don't do it!  *grin*

> Well, there are modules said to be safe for doing "from xyz import *":
> Tkinter for example. Just be sure your module contains only methods
> garanteed to have unique names.
> > always do:
> >
> > import MyReallyLongModuleName as my

Another way to say this is:

import MyReallyLongModuleName
my =3D MyReallyLongModuleName

Imported modules can be treated as objects, just like numbers and strings,
so it's fairly easy just to rebind them with another name.  We can even
keep them in a list if we're in a wacky mood:

>>> import re
>>> import os
>>> import math
>>> modules =3D [re, os, math]
>>> modules
[<module 're' from
<module 'os' from
<module 'math' from

Sorry, I guess I'm getting off track.  *grin*

There are other shortcuts that are kosher when we want to easily access
module functions.  Although 'from xyz import *' is usually not a good
idea, there's a weaker version that's pretty safe:

    from xyz import some_function

Instead of pulling everything, we can pull out a controlled number of
functions.  For the os.popen() example, it's perfectly ok to do:

from os import popen

and then use 'popen()' anywhere you want.

One advantage of this form is that it makes it much easier to pull
functions from multiple modules without everything being one muddled mess.
This form of the statement is more explicit about what kinds of things
we'll pull from the module, and much nicer from a program maintainer's
point of view.

Good luck to you!

More information about the Tutor mailing list