Dario
Dario

Reputation: 321

Python: Relative imports

I'm trying to use a package that has the following structure: enter image description here

The file prova.py contains only the following line:

import bipartite_class

while bipartite_class.py has the following initial lines:

from .nes import *
from .mod import *
from .graphs import *
from .contrib import *
from .null import *
from .tests import *

from getref import *

import pickle
import tempfile
import os
import numpy as np
import networkx as nx

import os.path

When I try to compile prova.py I get the following error:

Traceback (most recent call last):
  File "prova.py", line 1, in <module>
    import bipartite_class
  File "/Desktop/CD_BEST/Bipartito/bipy-master/bipy/bipartite_class.py", line 1, in <module>
    from .nes import *
ValueError: Attempted relative import in non-package

If I try to remove the dots in bipartite_class.py I get:

Traceback (most recent call last):
  File "prova.py", line 1, in <module>
    import bipartite_class
  File "/Desktop/CD_BEST/Bipartito/bipy-master/bipy/bipartite_class.py", line 1, in <module>
    from nes import *
  File "/Desktop/CD_BEST/Bipartito/bipy-master/bipy/nes/_init_.py", line 5, in <module>
    from nodf import *
  File "/Desktop/CD_BEST/Bipartito/bipy-master/bipy/nes/nodf.py", line 3, in <module>
    from ..mainfuncs import *
ValueError: Attempted relative import beyond toplevel package

What should I do?

Upvotes: 0

Views: 85

Answers (1)

Jasmijn
Jasmijn

Reputation: 10452

It looks like you're using this: https://github.com/tpoisot/bipy and that prova.py is your addition (it would be nice if you include this kind of information in your question in future questions!)

The problem is that bipartite_class is not a free-standing module, but is a part of the package bipy. That means you need to import it from outside the package. You need to move prova.py one directory up, to bipy-master, and change its contents to:

from bipy import bipartite_class

and then you should be able to run prova.py.


Even better would be to actually install bipy. Because the project includes a setup.py, you can run:

python setup.py install

Then you can import bipy from anywhere, so you can put your programs that use it in their own directory.

Upvotes: 1

Related Questions