the demise of 'from foo import * and its implications?

Jeremy Hylton jeremy at alum.mit.edu
Sat Mar 3 17:18:34 EST 2001


>>>>> "RB" == Robin Becker <robin at jessikat.fsnet.co.uk> writes:

  RB> my preference would be that statements legal in one context
  RB> should be legal in another where they make sense. I cannot see
  RB> how using import * or eval etc in nested scopes is somehow
  RB> obviously bad or different from the same usage in non-nested
  RB> scopes. The fact that the prohibition comes from making things
  RB> easier for the compiler adds to my confusion.

Using import * in function's is asking for trouble, because it makes
it impossible for someone reading the code to know what a variable
refers to.  Consider this hypothetical bit of code:

    from string import *

    def f(x):
        from amodule import *
        return strip(x)

What does strip refer to?  Feel free to assume Python 2.0 name
binding rules.  As a reader of the code, you'll have to know what
names are exported by string and amodule.  That makes reading the code
hard.  As a program evolves, it gets even worse.  If a new function is
added to amodule, the module using import * may break.  If you add a
function mumble() to your module and call it from f, it may break
because you forgot that amodule defines a mumble, too.

Python has always had static, but not-nested scopes.  The use of
import * and exec without in-clause in functions has always clashed
with the static nature of name binding.  Code that actually uses
import * or exec in functions can be quite confusing to figure out.
(Not always, but often.)

One other thing you're confused about is that the prohibition comes
from making things easier for the compiler.  That's bunk.  The
prohibition comes because there is no reasonable and intuitive
semantics for these features in the presence of nested scopes.  When
the issue first came up on python-dev, two seasoned Python programmers
explained what the obvious semantics where.  They chose completely
opposite semantics.  There's just no sensible meaning to assign to
this kind of code in most cases.

Jeremy




More information about the Python-list mailing list