Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does "Mark directory as sources root" really do?

In Pycharm, if you right click in a folder inside your project, you can mark it as sources root, so then you can import modules from this folder and subfolders.

However doing it this way will only make your program runnable inside Pycharm, if I try to execute from outside Pycharm (eg from the console) it will complain that certain modules are not found, which is the problem that I'm facing.

If I mark a certain folder as sources root my program runs fine, but I need to understand what does it do so I can configure the program to find this modules even if not using Pycharm.

I want to know what does this option exactly do, and how can I get the same behaviour without using it.

It is just adding a __init__.py file in the root folder? Is it doing something like:

import sys
sys.path.insert(0, my_folder)
like image 996
Sembei Norimaki Avatar asked Aug 05 '19 14:08

Sembei Norimaki


People also ask

What is source root directory?

The project source directory is typically the topmost, or “root” directory that contains most of the source files. You might think of this as the “home” directory of the project. Source Insight normalizes project file names relative to this directory.

What is source root?

Source roots (or source folders; shown as ). These roots contain the actual source files and resources. PyCharm uses the source roots as the starting point for resolving imports. The files under the source roots are interpreted according to their type.

What is the root of a project directory?

The project root is the folder which is the parent for all the project sources. By default, all subfolders in this folder are treated as sources and their files are involved in indexing, searching, parsing, code completion, and so on.

How do I mark a directory as root terminal?

from pycharm>Settings>Project>Project Structure select your project and from the file tree, select your django project directory then click the blue folder Source button to define the directory as your source.


1 Answers

First __init__.py marks a directory as a regular package directory(this is pre 3.3, in 3.3+ its not required anymore). With this, python will look for submodules inside that directory for imports.

"Mark directory as sources root" sets the PATH(or PYTHONPATH) for the environment. In shell, it will be like,

export PYTHONPATH="${PYTHONPATH}:/your/source/root"

PYTHONPATH holds the default search path for module files. This will enable the interpreter to search for the modules in the appended path. The default value is installation dependent(normally it contains path to Python binaries).

You can also manipulate this search path using sys.path from inside a python file.

like image 136
Carrot Avatar answered Nov 06 '22 14:11

Carrot