Python; Cant import module from other directory

Question:

I am trying to decompose my program on python. I have read a lot of information and other answers about how import works, but still cant understand how exactly.

I want to use my module Graph.Graph2D for implementation in InteractiveGraph2D. Before importing it, I add path to this module. But it tells NameError: name 'Graph2D' is not defined.

Project path:

~/MyData/Python/Pygame/RoadSearchAlgorithm/src

Module path:

~/MyData/Python/Pygame/MY_MODULES/Graph

Code:

# ~/MyData/Python/Pygame/RoadSearchAlgorithm/src/Graph_package/InteractiveGraph2D.py

...
sys.path.append('./')
sys.path.append('/home/rayxxx/MyData/Python/MY_MODULES')
try:
    from Graph.Graph2D import Graph2D, ...
    ...
except Exception as e:
    assert (e)

class InteractiveGraph2D(Graph2D):
    ...

What’s the problem?

I tried to look at paths, list of imported modules. The Graph module presented in it.

Asked By: rayxxx

||

Answers:

You should make the Graph module installable by adding a setup.py file to it’s directory (doc). Then you could install it with pip and import it like any library.

Answered By: Lenn Lewis

You say that the modules path is ~/MyData/Python/Pygame/MY_MODULES/Graph while in the python code you added the string '/home/rayxxx/MyData/Python/MY_MODULES' to the os.path. Maybe the point is this

Answered By: Ulisse Rubizzo

this is a common error, when you run a python script it looks at the dir where you are running the script so four your case when you run

from Graph.Graph2D import Graph2D, ...

From

~/MyData/Python/Pygame/RoadSearchAlgorithm/src

Python at most can import from src.

Some solution, make your module installable by adding a setup in MY_MODULE, then doing a pip install . in that folder, here is an example How to setup.
And maybe you need to add an init.py to MY_MODULES/, check hereDo I need init.py

Another solution is to add MY_MODULES/ to python path, avoid this if possible but here is an example Add to python path.

Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.