SyntaxError: 'import *' not allowed with 'from .'

Ben Finney bignose+hates-spam at benfinney.id.au
Mon Jan 14 18:01:07 EST 2008


George Sakkis <george.sakkis at gmail.com> writes:

> Unless I missed it, PEP 328 doesn't mention anything about this.
> What's the reason for not allowing "from .relative.module import *'
> ?

It makes the code much harder to follow visually and inspect with
static analysis tools, since there's no way to see where names come
from in the code. It defeats the purpose of separate namespaces,
confusing the imported module's names with the current module's names
in a way that makes the indistinguishable.

If you want to use all or most of the names in a module, keep them in
their own namespace:

    import spam
    import eggs

    spam.do_stuff()
    eggs.do_stuff()

If you don't like the name of the module, then use whatever one suits
you:

    import your_mother_was_a_hamster as spam
    import your_father_smelled_of_elderberries as eggs

    spam.do_stuff()
    eggs.do_stuff()

Both of these are superior to 'from spam import *' because it's clear
(to the reader and to static analysis tools) where every name comes
from: unqualified names must be defined in the current module, any
ones from the imported module are qualified with the module name.

You also, in cases like the above example, avoid unknowingly
clobbering existing names by importing from another module into the
current namespace.

-- 
 \       "Never use a long word when there's a commensurate diminutive |
  `\                                 available."  -- Stan Kelly-Bootle |
_o__)                                                                  |
Ben Finney



More information about the Python-list mailing list