0

I'm using pycharm and was unable to navigate to the base class from the child class code following format for the following project structure

dir 1 Base class dir 2 Child class when I import the class using this way, pycharm is not able to navigate to the base class but the Python file executes properly

sys.insert.path("../dir1/")
import baseclass

When I import the class using

import dir1.baseclass

Makes pycharm understand where the base classes and I navigate to it using shortcuts. The Python scripts executes properly with pycharm in this case.

I am not able to understand how python automatically can figure out the path of baseclass.py in import dir1.baseclass because I'd never gave the relative or absolute path of dir1. Does it automatically assume that dir1 is going to be at the same directory level as that of child class.

And why does pycharm behave differently with these statements for navigation works the same for execution?

1 Answer 1

1

Basically, when you called the Python to run an archive, it defined the directory that contain this archive as the working directory. After that, the Python's interpreter has tried to resolve the imports, and to achieve that, it first searched these imports inside the working directory.

However, as you used import dir1.baseclass, you told to Python that the file baseclass was not been in the working directory, but in one of its sub-directories, in this case, inside of ../WorkingDirecory/dir1/, so, the python navigated to there and imported the class.

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you for the comment. So from what I understand, I really do not need to do any sys.path.insert for any subdirectory within the working directory. I just provide a relative path to that and Python will pick the module itself. Is this correct? I just need one more confirmation. Is this code guaranteed to work with any IDE or even if someone runs the Python script standalone? It is obviously working on my machine but I need to make sure that it will work as long as the directory structure remains the same. Thanks!
I just found that if I invoked the Python script from his C++ process where the current working directory of the child Python process is set to the actual directory where the script is stored , then the sys,insert.path... Approach works but the import dir1.baseclass does not. I need to use import dir1.baseclass because then Pycharm is able to navigate through baseclasses. Is there a way to make it work? By changing python environment for example

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.