Why import only at module level?

Paul Rubin http
Thu Feb 19 04:03:58 EST 2004


That's what the Python style guides advise.  They 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?  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.  So the pollution is really
serious in that case, you're spewing all the names from the imported
module into your own module.  And I know that "import *" is considered
uncool these days, but sometimes you really do want to just grab all
those symbols, and the whole point of wanting the import inside the
function is to contain the big import to a limited scope where they
won't conflict with your own symbols.

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



More information about the Python-list mailing list