Skip to main content
Troubleshooting

How to resolve the “You should not try to import numpy from its source directory” error when using AWS Lambda with Python

By March 18, 2024No Comments

An “Unable to import module” error is generated when the AWS Lambda environment can’t find a specified library in the AWS Lambda deployment package whether you are packaging your dependencies into your project or using a Lambda layer (recommended).

For the purposes of this post, we will go with the better option of using Lambda layers. If you need reasons why Lambda layers are better, please check out our article on the differences between Lambda layers vs packaging dependencies into the project code.

Note: When you create a Lambda layer, you must place the libraries in the /python or python/lib/python3.x/site-packages folders. It’s a best practice to create the Lambda layer on the same operating system (OS) that your Lambda runtime is based on. For example, Python 3.12 is based on an Amazon Linux 2023 Amazon Machine Image (AMI). So, create the layer on an Amazon Linux 2023 OS.

To create the correct folder structure and upload zip for the layer, run the following code. Include other dependencies as needed. This example only showcases how to remove the numpy error.

mkdir -p lambda-layer/python
cd lambda-layer/python
pip3 install --platform manylinux2014_x86_64 --target . --python-version 3.12 --only-binary=:all: numpy

This code creates a directory called lambda-layer with a sub-directory called python which is necessary for the dependencies to be used on the layer. Next we cd into that directory and install the correct python and runtime version of the numpy package.

Note: Update the platform parameter for your function type. For a x86_64 Lambda function, set the value to manylinux2014_x86_64. For an arm64 function, set the value to manylinux2014_aarch64. Update the python-version parameter to the same version that your Lambda function uses.

That’s it! You should now be able to zip this folder using the following code:

cd ..
zip -r layer.zip python

Lastly, upload this into a Lambda layer and attach to your function. You can read up on how to create and attach a Lambda layer in our other articles.