Skip to content Skip to sidebar Skip to footer

Add Path To Python Package To Sys.path

I have a case for needing to add a path to a python package to sys.path (instead of its parent directory), but then refer to the package normally by name. Maybe that's weird, but

Solution 1:

One helpful fact is that adding something to the python path is different from importing it into your interpreter. You can structure your modules and submodules such that names will not clash.

Look here regarding how to create modules. I read the documents, but I think that module layout takes a little learning-by-doing, which means creating your modules, and then importing them into scripts, and see if the importing is awkward or requires too much qualification.

Separately consider the python import system. When you import something you can use the "import ... as" feature to name it something different as you import, and thereby prevent naming clashes.

You seem to have already understood how you can change the PYTHONPATH using sys.path(), as documented here.

Solution 2:

You have a number of options:

  • Make a new directory pyutilsdir, place pyutils in pyutilsdir, and then add pyutilsdir to PYTHONPATH.
  • Move the experimental code outside of /home/me/python and add python to your PYTHONPATH.
  • Rename the experimental modules so their names do not clash with other modules. Then add python to PYTHONPATH.
  • Use a version control system like git or hg to make the experimental modules available or unavailable as desired.

    You could have a master branch without the experimental modules, and a feature branch that includes them. With git, for example, you could switch between the two with

    git checkout [master|feature]

    The contents of /home/me/python/pyutils (the git repo directory) would change depending on which commit is checked out. Thus, using version control, you can keep the experimental modules in pyutils, but only make them present when you checkout the feature branch.

Solution 3:

I'll answer to my own question since I got an idea while writing the question, and maybe someone will need that. I added a link from that folder to my site-packages folder like that: ln -s /home/me/python/pyutils /path/to/site-packages/pyutils

Then, since the PYTHONPATH contains the /path/to/site-packages folder, and I have a pyutils folder in it, with init.py, I can just import like:

from pyutils import mymodule

And the rest of the /home/me/python is not in the PYTHONPATH

Post a Comment for "Add Path To Python Package To Sys.path"