Why import only at module level?

Michael Hudson mwh at python.net
Thu Feb 19 12:41:50 CET 2004


Paul Rubin <http://phr.cx@NOSPAM.invalid> writes:

> That's what the Python style guides advise.  They 
                                               ^^^^
I do wish people would stop using this word in this sort of context...

> don't seem to like
> 
>    def frob(x):
>       import re
>       if re.search('sdf[234]xyz', x): ...
> 
> instead preferring that you pollute your module's global namespace
> with the names of all your imports.  What's the point of that?

What's the problem with that?

> It gets worse when you want to do something like
> 
>    def dispatch(obj):
>       from types import *
>       if type(obj) == ListType: obj_list(obj)
>       elif type(obj) == FunctionType: obj_fcn(obj)
>       ...
> 
> here you actually get a syntax warning that "from ... import *" is not
> ALLOWED except at the module level.

The problem HERE is for nested scopes; it's impossible to know in

def f():
    from baz import *
    def g():
        return y

where y is coming from (i.e. is it a captured binding or a global).

> So what's the reason for the syntax warning, and for the convention of
> putting the imports at the top of the module?

I think putting imports at the top is just so you can find them
easily, and at a glance see which modules a given module imports.

Cheers,
mwh

-- 
  "The future" has arrived but they forgot to update the docs.
                                        -- R. David Murray, 9 May 2000



More information about the Python-list mailing list