Py3: Import relative path module

Peter Otten __peter__ at web.de
Mon Nov 1 12:36:26 CET 2010


Gnarlodious wrote:

> On Nov 1, 2:16 am, Steven D'Aprano <steve-REMOVE-
> T... at cybersource.com.au> wrote:
>> On Mon, 01 Nov 2010 01:08:52 -0700, Gnarlodious wrote:
>> > On Oct 31, 11:09 am, Дамјан Георгиевски wrote:
>> >> from .. import Data.DumpHT as DumpHT
>>
>> > That doesn't work. Any more ideas?
>>
>> Define "doesn't work".
> 
> LOL.
> I get error:
> 
>     from .. import Data.DumpHT as DumpHT
>                        ^
> SyntaxError: invalid syntax
> 
> Rewording gets me closer:
> 
>     from ..Data import DumpHT
> ValueError: Attempted relative import in non-package
> 
> I do have the empty __init__.py file in the Data folder. What is
> wrong?

Remove the directory containing the importing file from your sys.path.
E. g. if you have

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

only the parent of alpha should be in your sys.path. Then to import 
alpha/gamma/two.py from alpha/beta/one.py use

from ..gamma import two

Peter



More information about the Python-list mailing list