Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

'Attempted relative import in non-package' although packages with __init__.py in one directory

I have a module named extended.py which contains the following line:

from .basic import BasicModule 

and the file basic.py resides in the same directory as does __init__.py. However, when I try to run it as:

python extended.py 

I get the error:

ValueError: Attempted relative import in non-package 

Also adding the line:

from __future__ import absolute_import 

does not solve the problem. Maybe I am too tired to see the obvious - but I don't see the problem here.

like image 676
Alex Avatar asked Feb 02 '13 17:02

Alex


People also ask

How do you use relative import in Python?

Relative imports use dot(.) notation to specify a location. A single dot specifies that the module is in the current directory, two dots indicate that the module is in its parent directory of the current location and three dots indicate that it is in the grandparent directory and so on.

What is __ package __?

That is, if a module is in a package, __package__ is set to the package name to enable explicit relative imports. Specifically: When the module is a package, its __package__ value should be set to its __name__ .


1 Answers

Relative imports only work for packages, but when you importing in extended.py you are running a top-level module instead.

The current directory may hold a __init__.py file but that doesn't make exended.py part of a package yet.

For something to be considered a package, you need to import the directory name instead. The following would work:

main.py  packagename\     __init__.py     basic.py     extended.py 

then in main.py put:

import packagename.extended 

and only then is extended part of a package and do relative imports work.

The relative import now has something to be relative to, the packagename parent.

like image 190
Martijn Pieters Avatar answered Sep 23 '22 09:09

Martijn Pieters