MousaZeidBaker/aws-lambda-typing

Allow import of events and other deeper types

Closed this issue · 2 comments

We should be able to easily import deeper types other than what is defined in aws_lambda_typing/__init__.py. Editors have a hard time navigating the types when I need to explicitly define types for classes like SQSMessage. Currently I have to manually import them with

from aws_lambda_typing.events.s3 import S3EventRecord
# or

from aws_lambda_typing.events import s3

for example. But vscode and pycharm isn't able to find the paths easily. Though pycharm is a bit better at it.
What seems to work well for me is to update the imports like so

# aws_lambda_typing/__init__.py
from aws_lambda_typing import context, events, responses

then in each of the 3 types, in their init files, just import the files. so for events, it would be

# aws_lambda_typing/events/__init__.py

from . import (api_gateway_proxy, cloud_watch_events, cloud_watch_logs,
               code_pipeline, config, dynamodb_stream, kinesis_firehose,
               kinesis_stream, mq, s3, s3_batch, ses, sns, sqs

This should make importing easier. It will likely break old imports but in the top level init, you can keep those in as python wont import a file again once it's been loaded. This allows me to do this, and have the editors easily know what is where.

from aws_lambda_typing import context, events

def handler(event: events.sqs.SQSEvents, context: context.Context):
    pass

Hi @autoferrit , thanks for opening an issue.

Wouldn't it be enough if we just add the missing sub types directly in aws_lambda_typing/__init__.py? Then you will be able to import sub types as the following image shows

import_deeper_types

After some rethinking, I see the value in having a hierarchy for the sub types, but it would be nice if one can import Events directly from the events object, e.g. events.sqs.SQSMessage for sub types and events.SQSEvent for events.

I could achieve what's mentioned above by keeping aws_lambda_typing/__init__.py empty and then

# aws_lambda_typing/events/__init__.py

from .sqs import SQSEvent
# other types goes here

and usage would be

from aws_lambda_typing import context as context_, events


def handler(event: events.SQSEvent, context: context_.Context) -> None:

    for record in event['Records']:
        print(record['body'])

    print(context.get_remaining_time_in_millis())
    
    message: events.sqs.SQSMessage

and yes IDEs (at least PyCharm) helps with navigation, see following screenshots

tmp

tmp2