Py3: Import relative path module

Peter Otten __peter__ at web.de
Wed Nov 3 14:50:45 CET 2010


Peter Otten wrote:

> Gnarlodious wrote:
> 
>> On Nov 3, 2:51 am, Peter Otten wrote:
>> 
>>> Slightly generalized: have the importing module print its __name__.
>>> There has to be at least one dot in the name for
>>>
>>> from .. import whatever
>>>
>>> to succeed.
>> 
>> Just spent about 3 hours trying every permutation I could think of,
>> and searching Google for exactly how to do it, but all I get is:
>> 
>> ValueError: Attempted relative import in non-package
>> 
>> How do I import a module so that a dot will appear in its name?
> 
> Make sure the no path in sys.path leads into a directory that contains an
> __init__.py. In particular, ensure that you aren't invoking the python
> interpreter from a working directory that contains an __init__.py and that
> the main script is in a directory that doesn't contain an __init__.py.
> 
> Peter

Here's a working example that you can use as a starting point:

$ tree
.
|-- alpha
|   |-- __init__.py
|   |-- beta
|   |   |-- __init__.py
|   |   `-- one.py
|   `-- two.py
`-- main.py

2 directories, 5 files
$ cat main.py
import alpha.beta.one
$ cat alpha/beta/one.py
from ..alpha import two
$ cat alpha/two.py
print "success!"
$ python main.py
success!

Peter



More information about the Python-list mailing list