Best practices with import?
Erik Max Francis
max at alcyone.com
Sat Jul 28 21:41:40 EDT 2001
Tom Bryan wrote:
> I've been using Python off and on for over two years. I've been
> teaching
> my wife Python, and she recently asked me how/where she should use
> import. I realized that I have no idea what the best idioms are and
> what
> arguments support doing it one way or another. For example, if I have
> a
> module that uses string, should I put an 'import string' at the top of
> the
> module? Should every function that needs the module import it?
> Sometimes
> I see modules that use both imports at the module level and at the
> function
> level. Why would I want to do that?
Multiple imports of the same module aren't expensive, since such imports
are cached (that is, it only _actually_ imports the file the first time
through). Using imports deep inside your code rather than all at the
top is just a matter of style.
I have been known to use interspersed imports (although rarely) in
functions in a module that are really just test functions or are the
main function (that gets executed when you run the module itself,
__name__ == '__main__'), where the function is somewhat disconnected
from the rest of the module (because all it does is drive the classes in
the module either as main or as a separate test routine) and uses some
system modules that the rest of the module doesn't need.
So, for instance, if I had a module that did some grunt work but no I/O
(so I didn't need to import sys for sys.stdin, sys.stdout, etc.) and in
it I put a main function that throws up a prompt and runs a little test
harness, I might do:
# gurgle.py
import ... # main imports for module proper
# module code
def main():
import sys # here's the only place that sys gets used
lines = sys.readlines()
# do something with lines ...
if __name__ == '__main__':
main()
I'm really not sure what the value would be in deleting the module after
you're through with it, except perhaps to clean up namespaces, which I
wouldn't think would be useful if, say, it were defined in the scope of
a function.
--
Erik Max Francis / max at alcyone.com / http://www.alcyone.com/max/
__ San Jose, CA, US / 37 20 N 121 53 W / ICQ16063900 / &tSftDotIotE
/ \ Many situations can be clarified by the passing of time.
\__/ Theodore Isaac Rubin
Kepler's laws / http://www.alcyone.com/max/physics/kepler/
A proof of Kepler's laws.
More information about the Python-list
mailing list