AWS Lambda Decorators

Sep 9, 2018 · 374 words · 2 minutes read awspythonserverless

A couple months ago I learned about the cool Python module, lambda-decorators by Daniel Schep. If you aren’t familiar with decorators, they’re a way to alter a function by wrapping it in another function. They can be useful in many cases, such as when you have boiler plate code that you want to apply to different functions.

AWS Lambda is am event-driven serverless computing service and a very easy to expose application code to other services (e.g. API Gateway, EC2 instances, etc.).

I prefer to have very terse Lambda functions and keep as much of the application logic in a module. The benefit to this is that I can re-use the module code elsewhere.

One of my pain points with AWS Lambda is that the event object is so different depending on the event source – different event sources put parameters in different places and you pretty much always need to write custom code to map them to your function parameters. You can, of course, just having different Lambdas for each event source type but then you’re just copying/tweaking your Lambda code (not very DRY).

The lambda-decorators module solves my problem by letting me put a decorator that parses the event on the handler function. The module has decorators for executing code before or after the handler is called (or both) and you can write your own decorators.

Here’s a quick example of how you can use decorators in AWS Lambda to parse the event source:

from lambda_decorators import before

@before
def parse_event_source(event, context):
    # SQS events have 'Record' key
    if 'Record' in event:
        ...
    # API Gateway proxy request events have 'headers' key
    elif 'headers' in event:
        ...
    # Lambda could be invoked directly
    else:
        ...
    return event, context

@parse_event_source
def lambda_handler(event, context):
    # Application code
    ...
    return event, context

In this example the @before decorator on our parse_event_source function ensures that it is executed before the lambda handler. This means that event will be the result of parse_event_source when the handler runs instead of the event from the event source.

There are a lot of useful things you can do with Lambda decorators to reduce boiler plate code. For example, logging the event before executing the handler or reformating the output afterward.