'Call function from another python file in AWS Lambda

I have a lambda deployment package containing two python files, file1.py and file2.py. I need file1.py to call a function from file2.py and here's how I did it.

from file2 import function1

variable1 = function1()
print(variable1)

The above method works when I am in my virtual environment, but when I upload the deployment package to Lambda, I am getting a None result from function1.

PS: file2.py works perfectly and function1 can return the desired output when I run it individually.



Solution 1:[1]

The solution is to ensure that the "Handler" value that you configure in AWS Lambda contain at least 2 . periods. To achieve this you need to put your code within a directory in your AWS Lambda code zip file and make that directory a module by adding an empty __init__.py file. The resulting structure looks like this

.
??? app
?   ??? __init__.py
?   ??? file1.py
?   ??? file2.py

And you now change the "Handler" value from file1.lambda_handler to app.file1.lambda_handler (Handler in the 1st file). More explanation from this answer.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Allan Chua