I have put the question in the figure below:
EDIT The question put next to the figure is:
How do I make script_A1 import a function from script_B2?
Similar questions have been asked before. But most answers suggest to add the module/script/package(whatever) to the PATH variable. For example:
sys.path.append('...')
But adding the module to the PATH variable just feels so wrong. I do not want to alter my system in any way. When my application closes, I want my Python environment to be clean and 'untouched'. I'm afraid that adding uncontrolled modules to the PATH variables on my system will cause headaches later on.
Thank you for helping me out :-)
We can use sys. path to add the path of the new different folder (the folder from where we want to import the modules) to the system path so that Python can also look for the module in that directory if it doesn't find the module in its current directory.
Import in python is similar to #include header_file in C/C++. Python modules can get access to code from another module by importing the file/function using import. The import statement is the most common way of invoking the import machinery, but it is not the only way.
To import a module from another path, you first need to import the sys module as well as any other Python modules that you would like to use in your program. The sys module is provided by the Python Standard Library and it provides functions and parameters that are system-specific. The path.
So there's four different ways to import: Import the whole module using its original name: pycon import random. Import specific things from the module: pycon from random import choice, randint. Import the whole module and rename it, usually using a shorter variable name: pycon import pandas as pd.
You can use a trick of adding the top folder to path:
import sys
sys.path.append('..')
import folderB.something
You can also use imp.load_source if you prefer.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With