Interview Prep/Python for DevOps/Language essentials & functions

What is a closure? Give a DevOps-flavoured example.

IntermediateConceptLanguage essentials & functions
Answer

A closure is an inner function that remembers variables from the enclosing scope after that scope has returned.

def make_tag_filter(key, value):
    def matches(resource):
        return any(t["Key"] == key and t["Value"] == value for t in resource.get("Tags", []))
    return matches

is_prod = make_tag_filter("Environment", "prod")
prod = [i for i in instances if is_prod(i)]

Watch the late-binding trap: lambdas created in a loop all see the last loop value unless you bind it, e.g. lambda r, k=k: ....

All Python for DevOps questions Roadmap: Python for automation

More on Language essentials & functions