Python: Main method with conditional position arguments
I often find that when writing Serverless Python methods I want to test them locally, rather than execute them on the remote server. To do that it makes sense to add a main method the python files so that you can simulate how the remote server is invoking the method.
One of the challenges I've found is that in many cases the function will be invoked with parameters and to simulate late I usually am adding the following method to every Serverless function file.
#file: my-serverless-function.py
# Main method that the Serverless function will execute
def main(args):
name = args.get("name", "stranger")
greeting = "Hello " + name + "!"
print(greeting)
return {"body": greeting}
# Code that will be executed when file is called from CLI
import argparse
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument("name", nargs="?", type=str, default=None)
args = vars(parser.parse_args())
main({k: v for k, v in args.items() if v is not None})
Hopefully someone doing the same thing might find this useful!