Posted on Leave a comment

Structure python code with packages – import functions from different files

A modular application is an application composed of loosely coupled, functional units called modules, and these modules can be linked together to form a larger application. When you implement your python applications you should create such structures instead of big monoliths.

In this guide I will demonstrate how you can call python function from different folders and files (called packages). I have created a flask application which has as entrypoint the file.

The solution is structured as shown below. The app folder is the root folder which contains all the code for the application. In the root hierarchy the is placed along with other folders as templates, static and helpers.

As I need to create a helper function that will request data from an external API I created a file named github inside my helpers folder and I defined a function within it.

The function is very simple and returns a simple message. Code for can be found below.

def my_function():
  return "Hello from function"

In order to call your helper functions from your main app or from another python package you should first import package

from helpers import github

and then use the function.

def home():
    return github.my_function()

This code will display on my flask main page the message of the function.

You can perform in such way any other activities by specifying your python file and then the function.


Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.