简体   繁体   中英

How does Python treat sys.path.insert(path) and import package_path.module differently

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM