Search code examples
pythonaws-lambdainitclass-method

Aws python lambda returns same result


I have my python code deployed to aws lambda where I get the same response no matter how many times I trigger it even with different inputs.

Here is my code:

handler.py

import lambdaLogicClass from “./lambdaLogicClass”

lgc = lgc.fetch_env()
def handler(event):
  lgc.run_process(event)

lambdaLogicClass.py

Class lambdaLogicClass:
  def __init__(self, env_value):
    self.x = env_value
    self.y = {}

  @classmethod
  def fetch_env(cls):
   return cls(env_value=os.getenv(env_key)

  def run_process():
    #some_logic

I get the same value from my lambda which invokes run_process method defined in my Class. I debugged and checked that after every run the class variables x doesn’t change in next run of lambda trigger.


Solution

  • Move the following code inside your Lambda function handler:

    lgc = lgc.fetch_env()
    

    So, the code should be:

    import lambdaLogicClass from “./lambdaLogicClass”
    
    def handler(event):
      lgc = lgc.fetch_env()
      lgc.run_process(event)
    

    As it stands, your lgc variable will only be initialized during a cold start. Any subsequent warm start will reuse the previous Lambda invocation's globally-scoped variables.

    See Understanding Container Reuse in AWS Lambda.