[Tutor] Import from project's lib directory?

Peter Otten __peter__ at web.de
Fri Aug 29 23:16:12 CEST 2014


leam hall wrote:

> Am I asking the wrong question? How do older apps with older versions
> of python (2.4.x) separate code into sub-directories? Do they?

Even new versions allow relative imports only inside packages. Given a tree

$ tree
.
├── alpha
│   ├── beta
│   │   ├── __init__.py
│   │   └── one.py
│   ├── gamma
│   │   ├── __init__.py
│   │   └── two.py
│   └── __init__.py
└── elsewhere
    ├── __init__.py
    └── three.py

You have to ensure that the *parent* of alpha is in sys.path. Then you can 
refer from alpha/beta/one.py to alpha/gamma/two.py with the statement

# in file alpha/beta.one.py
from ..gamma import two

but as far as I know no combination of dots lets you refer to modules 
outside the package (like elswhere/three.py in the example). You need an 
absolute import for that.




More information about the Tutor mailing list