Py3: Import relative path module
Peter Otten
__peter__ at web.de
Mon Nov 1 12:02:25 EDT 2010
Gnarlodious wrote:
> On Nov 1, 5:36 am, Peter Otten wrote:
>
>> Remove the directory containing the importing file from your sys.path.
> I removed all sys.path customizations and rebooted.
>
> In the following scenario, I am programming in one.py attempting to
> import Data.py which is in the alpha folder:
>> $ tree
>> .
>> `-- alpha
>> |-- __init__.py
>> |-- beta
>> | |-- __init__.py
>> | `-- one.py
>> `-- gamma
>> |-- __init__.py
>> `-- two.py
>
> However, all I can get is error:
>
> from .. import Data
> ValueError: Attempted relative import in non-package
>
> Why is the parent folder not recognized as a package? Because right
> now I am liberally using sys.path, which works but is a little too
> messy.
If you didn't add '/path/to/alpha' to your path explicitly then you may be
starting one.py as a script with
$ python /path/to/alpha/beta/one.py
one.py then becomes the __main__ module instead of alpha.beta.one.
Or your working directory is /path/to/alpha and you import one.py with
import beta.one
which makes beta instead of alpha the toplevel package.
Peter
More information about the Python-list
mailing list