Search code examples
pythongitpython-3.xgithubpython-module

Class Modules in Far-Off Places


Class Modules have to be in the working directory in order to be imported to a python program. However, I want to keep my individual main programs in separate directories based on use, and not have all programs and all classes jammed into one enormous directory.

What can I add to my scripts to point them to the correct module directory? Even better: can I make my module directory on a repo like GitHub and import for from there?


Solution

  • Python modules need to be somewhere in Python's search path. This happens to include the working directory.

    There are many places to store one's modules, possibly the easiest is

    /usr/local/lib/pythonx.y/site-packages
    

    or

    /usr/local/lib/pythonx.y/dist-packages
    

    (whichever one is on your system).

    Once in there you should create a directory for your stuff, create an empty __init__.py file in that directory, then copy your modules into it:

    sudo mkdir MyStuff
    sudo touch MyStuff/__init__.py
    sudo cp /home/me/my_module1.py MyStuff/
    sudo cp /home/me/my_module2.py MyStuff/
    

    and then in your scripts you can

    from MyStuff import my_module1