pythonpython-module

Importing a folder that has same name as a package


Let say I have a folder Pkg1, and a library also called Pkg1 (installed elsewhere) on the computer.

I also have a file run.py at Pkg1 > scripts > run.py.

I want to do:

from Pkg1 import Function1

but this will import the default library Pkg1 that I have installed earlier.

How do I change the import statement so that it imports from the current folder instead of the library?

P/S 1: I already have __init__.py inside Pkg1 folder

P/S 2: I know it is importing from the library because I tried to import

from Pkg1 import CURRENT_LOCATION

and it imports the location of the library, not the folder.


Solution

  • as put in the comments, for the scenario of

    I am contributing to an open-source package. Then I both want to have the package working (for my other projects), but I also need to maintain another version of it that I am working on?

    You should REALLY be using virtual environments, and install the version of the package you are working on with the pip -e flag, so it creates an editable install, and your inplace changes are visible in the imports.

    You can learn more about virtual environments here: https://docs.python.org/3/library/venv.html


    For other, possible, legitimate uses of "Importing a folder that has same name as a package", (which, I will make that clear again: does not include your use case. You need to use virtual envs there!), one can make some careful manipulation of the sys.path special list before issuing the import statement.

    sys.path is a plain Python list, in the module sys .It can be "appended", "insert"ed to or have members removed or re-ordered, and it is used "in real time" whenever the import mechanism is used.

    That could change the priority for folders that are scanned for import names. Beware that if the not-wanted module is imported before your sys.path manipulation code is located, that one will be already loaded, and your import-statement will just make that one available in the current namespace, not load the module from the intended folder.