What are `*args` and `**kwargs`, and how do you unpack them at the call site?
BeginnerConceptLanguage essentials & functions
Answer
*args collects extra positional arguments into a tuple; **kwargs collects extra keyword arguments into a dict. At a call site, * and ** unpack.
def run(cmd, *args, **kwargs):
return subprocess.run([cmd, *args], **kwargs)
params = {"Filters": [{"Name": "tag:env", "Values": ["prod"]}]}
ec2.describe_instances(**params)
The **params pattern is common with boto3 because you build optional arguments conditionally and only pass the ones you have.
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