Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use functions/classes from another directory

I am running Windows, Anaconda and PyCharm if that matters.

My directory looks as follows:

\MyMainDirectory
    \FunctionsLibrary
         ClassA.py
         ClassB.py
         functionA.py
         functionB.py
    \Project A
        main.py
    \Project B
        main.py

How can I with this directory setup use e.g. functionA.py and ClassA.py etc in my file e.g. \Project A\main.py, \Project B\main.py etc?

I have some common functions & classes that I would like to use in my separate projects "Project A" and "Project B".

Please note that "Project A" and "Project B" are two different projects in PyCharm.

Any help is appreciated!

like image 663
user1455613 Avatar asked Dec 05 '25 07:12

user1455613


2 Answers

You can include paths using 'sys'

# In your main.py
import sys
sys.path.append("../FunctionsLibrary")
import ClassA
import ClassB
like image 141
Algopark Avatar answered Dec 07 '25 20:12

Algopark


I think I found the best solution (at least for my application but probably for other people as well) which is to create a package (module) of the class or set of functions that is used by different project.

Then just install the package (module) that you have built. I simply followed this guide which works great.

https://packaging.python.org/tutorials/packaging-projects/

Please note: You do not have to upload the code to github, it is also possible to just have an offline version of your package.

Cheers!

like image 22
user1455613 Avatar answered Dec 07 '25 20:12

user1455613