Relative Python imports in a Dockerized lambda function
Learn how to create a Dockerized Lambda function that uses relative imports. Improve your maintainability of your code base by splitting responsibilities into different files.
Published Dec 14, 2024
Last Modified Dec 16, 2024
Relative Python imports can be tricky for lambda functions. I wrote a blog on this 3 years ago. But recently, I ran into the same issue with Dockerized lambda functions. So, I figured it was time for a new blog!
You can follow along with the steps or look at the result directly on GitHub.
Make sure you installed the AWS CDK cli.
Initialize the project:
First we will need to create the file and folder structure:
Now you will need to fill the
Dockerfile
, like this:We are using a Python base image that is based on Python 3.12. Next, we will copy in the
requirements.txt
file and the source code. We will install all dependencies listed in the requirements.txt
file and make sure that the handler
method is set as the CMD
.Next, we will need to fill our Python files with some code. In the
__init__.py
file, you can place the following content:Afterward, we will need to fill the `business_logic.py` file:
NOTE: The code used here could use multiple relative imports. This is possible because it is in a separate package. This example only shows one example in the `__init__.py` file. However, you can use multiple files here to improve the maintainability of your project.
For this example, I don’t need any dependencies, so we can keep the
requirements.txt
file empty. I included it in this example to illustrate how you can include dependencies as well.Our folders and files are in place, so it is time to add the Lambda function to the CDK construct. You can simply add it like this:
For this to work, you also need the following imports:
Note that we make sure that the code directory points to the directory that contains the
Dockerfile
and that we select the ARM platform for both the code and the function itself.Fast feedback is important, so there might be cases where you need to run the container locally. For this, you first need to build the container:
Note that this command can be executed from the project’s root. Next, we need to make sure it’s running before we can invoke it:
Afterwards, you can invoke the function as follows:
Relative imports can be tricky! You need to place your code in a package. This allows you to do relative imports within your own package. This will enable cleaner code, as you can split responsibilities into multiple files, making it easier to manage and maintain.
Photo by Kaique Rocha