Use functions/classes from another directory

Viewed 79

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!

3 Answers

You can include paths using 'sys'

# In your main.py
import sys
sys.path.append("../FunctionsLibrary")
import ClassA
import ClassB

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!

You can set environment variable PYTHONPATH like so:

export PYTHONPATH=/path/to/FunctionsLibrary:/path/to/Project\ A

And after this python will search in this directory too.

If you use virtualenv you can place this export to "activate" file or you can set environment variable using PyCharm(see in settings). I prefer using "activate" file

Related