(slightly OT): Python and linux - very cool

Peter Hansen peter at engcorp.com
Fri Aug 2 01:43:05 CEST 2002

(Cross-posting removed for this Python-specific reply.)

Roy Culley wrote:
> In article <3D492CAC.E3A37D82 at engcorp.com>,
>         Peter Hansen <peter at engcorp.com> writes:
> >
> > Nice post, and welcome to Python, but in this I think you leapt
> > to conclusions a little.  None of the above are actually common
> > issues in Windows with Python.  "from x import *" certainly works
> > properly, even though it's almost never a good idea (hint to newbies:
> > don't do that!).
> I'm a python newbie. How's about expanding on the hint. I just do (as
> an example):
> import os, re, sys, string
> Is that bad also? Maybe we can turn cola into a python tutorial
> newsgroup. :-)

(I've read the other fine responses and am adding a few more comments
of my own.  The others said most of what needs saying already.)

The above is not bad, except that you might find it more maintainable
(as well as a closer fit to the recommended Python style: see 
http://www.python.org/peps/pep-0008.html in the Imports section) if you 
split them onto individual lines:

import os
import re
import sys
import string

Definitely a bit more typing but depending on the module and your
coding style, you could benefit by keeping with this convention.

As for why "from ... import *" is bad, in addition to the other 
points raised, you can get into trouble if you are importing more
than just method names.  We recently had a bug caused by overuse of
this idiom where a module initially had a "global" which was 
initialized to None.  An initialize() function in the module was
supposed to be called to rebind the global name to an object,
but as it turned out another module managed to do a "from 
import *" before this initialization took place.  As a result,
the other module had a local name bound to "None" which was not
affected by the subsequent call to the initialization() function.

Had we done a simple, clean "import ..." instead, the other module
would have been referring to the name as modulename.globalname
and after initialize() was called it would be bound to the new
object instead of to None.

That might not be clear to a newbie, and I can see I've explained
it poorly so it's probably unclear to anyone. :(  Point is, there
are definitely cases where you can get in trouble with the "from"
technique so you'd best avoid it until you know enough Python to
understand exactly how you might get tripped up.


More information about the Python-list mailing list