0

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.

3 Answers3

0

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.

Lenn Lewis
  • 46
  • 5
0

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

  • Yes, it helped, but I must add `/home/rayxxx/MyData/Python/MY_MODULES` and `/home/rayxxx/MyData/Python/MY_MODULES/Graph` so it works. Do you know why? –  Nov 25 '22 at 14:43
  • It's strange the second one should be enough but did not you forget a Pygame in the path between Python and MY_MODULES? – Ulisse Rubizzo Nov 25 '22 at 15:45
  • 1
    Sorry, it's mistake, there is no `Pygame` word in `Graph` path. Seems, all works fine. –  Nov 25 '22 at 16:23
0

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.

Jonathan
  • 13
  • 5