Search code examples
pythonpython-3.xpython-importimporterror

Unable to import a function from outside the current working directory


I am currently having difficulties import some functions which are located in a python file which is in the parent directory of the working directory of the main flask application script. Here's how the structure looks like

project_folder
- public
--app.py
-scripts.py

here's a replica code for app.py:

def some_function():
    from scripts import func_one, func_two
    func_one()
    func_two()
    print('done')


if __name__ == "__main__":
    some_function()

scripts.py contain the function as such:

def func_one():
    print('function one successfully imported')


def func_two():
    print('function two successfully imported')

What is the pythonic way of importing those functions in my app.py?


Solution

  • Precede it with a dot so that it searches the current directory (project_folder) instead of your python path:

    from .scripts import func_one, func_two
    

    The details of relative imports are described in PEP 328

    Edit: I assumed you were working with a package. Consider adding an __init__.py file.

    Anyways, you can import anything in python by altering the system path:

    import sys
    sys.path.append("/path/to/directory")
    from x import y