Question about importing modules

Jeremy Bowers jerf at jerf.org
Sat Aug 21 23:13:45 EDT 2004


On Sat, 21 Aug 2004 14:59:36 -0400, pythos wrote:

> Newbie at python (but not programming) here...
> 
> I have a program that has "import os" at the top, and then later a call to
> utime() is made.  The python interpreter says "name 'utime' is not defined".
> But if I change "utime(...)" to "os.utime(...)" then it works fine.  Perhaps I
> am expecting the "import os" statement to work the same way as "import
> <package_name>.*" does in Java.  So is it the case that if I write "import os"
> in python, then I still need to write "os.utime(...)"?  Or is there something
> else wrong?  Thanks.

Taking a slightly different tack than your other repliers which I think
might be more educational in the long run, pop open a Python shell and do
an "import os". That creates a "module" object in the current namespace
which you can manipulate. Example:

Python 2.3.4 (#1, Jun  8 2004, 17:41:43) 
[GCC 3.3.3 20040217 (Gentoo Linux 3.3.3, propolice-3.3-7)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import os
>>> os
<module 'os' from '/usr/lib/python2.3/os.pyc'>
>>> dir(os) 
['EX_CANTCREAT', 'EX_CONFIG', 'EX_DATAERR', 'EX_IOERR', 'EX_NOHOST', 'EX_NOINPUT
', 'EX_NOPERM', 'EX_NOUSER', 'EX_OK', 'EX_OSERR', 'EX_OSFILE', 'EX_PROTOCOL', 'E
X_SOFTWARE', 'EX_TEMPFAIL', 'EX_UNAVAILABLE', 'EX_USAGE', 'F_OK', 'NGROUPS_MAX',
... whole lotta other stuff ...
 'stat', 'stat_float_times', 'stat_result', 'statvfs', 'statvfs_result', 'strerr
or', 'symlink', 'sys', 'sysconf', 'sysconf_names', 'system', 'tcgetpgrp', 'tcset
pgrp', 'tempnam', 'times', 'tmpfile', 'tmpnam', 'ttyname', 'umask', 'uname', 'un
link', 'unsetenv', 'utime', 'wait', 'waitpid', 'walk', 'write']

"os" is an object that can be passed around like anything else. (Though I
have yet to ever have need to pass around a module object I can imagine
rare cases where it might be useful.)

That's why you can also use "import" in a function, and the module object
will be local to the function. (You can not use "from os import *" for
various technical reasons, but that's usually not useful anyhow.)

"from os import *" loads the "os" object, then walks it and loads its
contents into your local namespace. This is a particularly bad idea for
"os" because it has function names like "open", "path", "wait", "write",
and a lot of other function names you're likely to collide with. It is
rarely a good idea for code, though I will confess to sometimes using
"from constants import *" in large programs, leaning on the ALL_CAPS
convention to indicate "constantness".



More information about the Python-list mailing list