DEV Community

Cover image for ImportError in AWS Lambda function
Tobias Haindl
Tobias Haindl

Posted on

ImportError in AWS Lambda function

I recently stumbled across an import error when deploying an AWS lambda function via SAM.

I used the following folder structure:

src/lambda.py
template.yml
Enter fullscreen mode Exit fullscreen mode

Lambda.py:

def lambda_handler(event, context):
    print('hello world')
Enter fullscreen mode Exit fullscreen mode

Template.yml:

AWSTemplateFormatVersion: '2010-09-09'
Transform: AWS::Serverless-2016-10-31
Resources:
  Lambda:
    Type: AWS::Serverless::Function
    Properties:
      Handler: src.lambda.lambda_handler
      Runtime: python3.8
      Events:
        SchedulingEvent:
          Type: Schedule
          Properties:
            Schedule: rate(5 minutes)
Enter fullscreen mode Exit fullscreen mode

Once deployed, the following error was raised:

Runtime.ImportModuleError: Unable to import module 'src.lambda': No module named 'src'
Enter fullscreen mode Exit fullscreen mode

Since I copied the template and the lambda code from another project I was really baffled why I didn't work out of the box. Then I realized the little __init__.py was missing in the source folder...

Don't forget to add an empty __init__.py file to the src folder if you use the same project structure!
If you set Handler to src.lambda in your template.yml the lambda environment is looking for a python module called src therefore a __init__.py is required.

Top comments (0)