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.

asked Nov 25, 2022 at 14:12

3 Answers 3

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

answered Nov 25, 2022 at 14:37
Sign up to request clarification or add additional context in comments.

3 Comments

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?
It's strange the second one should be enough but did not you forget a Pygame in the path between Python and MY_MODULES?
Sorry, it's mistake, there is no Pygame word in Graph path. Seems, all works fine.
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.

answered Nov 25, 2022 at 14:30

1 Comment

Is there other way, if I dont want to make it installable?
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.

answered Nov 25, 2022 at 14:48

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.