0

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?

khelwood
  • 55,782
  • 14
  • 81
  • 108
Mysterio
  • 2,878
  • 2
  • 15
  • 21

2 Answers2

1

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
Alec
  • 8,529
  • 8
  • 37
  • 63
1

1.

import importlib.util

def loadbasic():
    spec = importlib.util.spec_from_file_location("basic", os.path.join(os.path.split(__file__)[0], 'basic.py'))
    basic = importlib.util.module_from_spec(spec)
    spec.loader.exec_module(basic)
    return basic #returns a module
  1. Or create an empty file __init__.py in the directory.

And

  1. do not pollute your path with appends.
ilias iliadis
  • 601
  • 8
  • 15