PyCharm - attach project does not work, cannot import modules across projects
The PyCharm documentation (2023.1.3 community) says that if you select ‘attach’ when opening project B within already opened project A, you are creating a dependency of A on B and you will be able to use code from B. But this does not seem to work.
In my setup, I have project ‘emailgen’ already opened. I go ‘File > Open’ and find the project ‘nlp-communal’, then selected ‘Attach’. Now I have the view of both projects, their structures are shown below.
Now say within ‘emailgen' I have ai.emailgen.autocompose.autocompose.py and I want to use code from ‘nlp-communal’ within this file. I tried to type an import statement as ‘from ai.common….’, but this does not get recognised. As you can say, the pop-up suggestion does not show ai.common…. if I force it by typing the full module path and run the code, I get an error saying that the module and package does not exist.
What have I done wrong?
Thanks
Please sign in to leave a comment.
Hello,
I'm not sure if it's possible with a project structure like this. The problem is that the Python interpreter gets confused with similar paths (
project_one/src/ai
andproject_two/src/ai
), and it will use the first one from the main project. Technically, the attached project is simply added to the PYTHONPATH, and so you can import directories and modules from the attached project.You can reproduce this error outside PyCharm by specifying the PYTHONPATH variable with the path to the second project src folder, and you will get the same error (depending on which project path will be first, the error's behavior could be slightly different, but one ai directory will still be inaccessible for Python interpreter).
Thank you. I suppose in this case, the fix is to make sure the top levels of the two projects are different. E.g., project1/src/ai_1/… project1/src/ai_2/… ? Would this work?
Thanks