Relative-importing *

Ben Finney bignose+hates-spam at benfinney.id.au
Fri Jul 27 19:05:51 EDT 2007


rbygscrsepda at gmail.com writes:

>     from . import *
>     from .sibiling import *
>     from .. import *
>     from ..parent_sibling import *
> 
> ...and so on. The same error occurs:
>     SyntaxError: 'import *' not allowed with 'from .'

Interesting. I know that 'from foo import *' is frowned on and is
generally worse than importing names explicitly, but I wasn't aware
that it was officialy deprecated. The PEP introducing absolute and
relative imports <URL:http://www.python.org/dev/peps/pep-0328/>
doesn't mention it, except as a friendly "import * is *not* an option
:-)" aside.

> Why would it not let me import * from a relative module at all? I
> read that they're planning to make absolute imports the default, so
> I'd think that this sort of thing would become more common in the
> future.

I'd also like to know when this changed,and where it's documented.

While waiting, you should take it as an opportunity to remove the
blight of "from foo import *". All imports should explicitly import
names, not implicitly clobber the current namespace with whatever pops
out. Depending on the reason for the import, do one of the following:

    from foo import bar, baz, boris
    do_stuff_with(baz)

    import foo
    do_stuff_with(foo.baz)

    import uncomfortably_long_name as foo
    do_stuff_with(foo.baz)

All of these preserve the valuable trait of being able to trace, by
reading the program, the origin of every name in the current
namespace.

-- 
 \          "I hope if dogs ever take over the world, and they chose a |
  `\    king, they don't just go by size, because I bet there are some |
_o__)                Chihuahuas with some good ideas."  -- Jack Handey |
Ben Finney



More information about the Python-list mailing list