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: ....
More on Language essentials & functions
Why is Python the default scripting language in so many DevOps teams, and where would you not use it?BeginnerWhat is the difference between mutable and immutable types? Give examples.BeginnerWhat does assignment do in Python, and how do shallow and deep copies differ?BeginnerExplain the mutable default argument bug and how to fix it.IntermediateWhat is the difference between `==` and `is`?BeginnerWhat values are "falsy" in Python, and why does it matter in scripts?Beginner