Skip to content
Advertisement

Easiest way to import a function from a file in a different folder

Can I import a python module from a distant folder? (Possible duplicate of How to import a Python module from a sibling folder?)

Advertisement

Answer

In general, the git repo should have a requirements.txt if it is for general use. If it has one then you can run pip install requirements.txt

It is also fairly easy for the repo owner to generate this file. At the root of their project they can run pip freeze > requirements.txt. pip freeze lists all current dependencies and so this command outputs the result to requirements.txt.

As for your second point, it really depends on the package structure. If they want to expose the code in the package they may have imported it in one of the top level __init__.py files. Otherwise, you can always directly import by following the paths.

For example if your structure is:

project
    folder
        subfolder
            module

And module has a function called foo then you can import foo like so: from project.folder.subfolder.module import foo. Of course this assumes each of these directories has its own __init__.py file

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement