relative import broken?

Alex Martelli aleax at mac.com
Sat Apr 28 17:09:44 EDT 2007


Alan Isaac <aisaac at american.edu> wrote:

> Are relative imports broken in 2.5?
> Directory ``temp`` contains::
> 
>         __init__.py
>         test1.py
>         test2.py
> 
> File contents:
> __init__.py and test2.py are empty
> test1.py contains a single line::
> 
>         from . import test2
> 
> Python 2.5.1 under Win2000, cmd line execution,
> produces as output::
> 
>         Traceback (most recent call last):
>           File "F:\temp\test1.py", line 1, in <module>
>             from . import test2
>         ValueError: Attempted relative import in non-package
> 
> Why?

If you're running test1.py as your main module, then it's not part of a
package, so the relative import should indeed fail as you mention.
OTOH, something like:

$ python -c'from temp import test1'

from the parent directory of temp should work fine.  Since you don't
give us the exact command line you're trying to execute, it's impossible
to guess exactly what you're doing.


Alex



More information about the Python-list mailing list