Master Python’s *args and **kwargs: When to Use Each Parameter Style
This tutorial demonstrates Python’s universal *args and **kwargs parameters through step‑by‑step examples, comparing direct and unpacked argument passing, and shows how mixing regular parameters with **kwargs affects function calls and output for developers.
We start with a simple function that accepts arbitrary positional and keyword arguments:
def test(*args, **kwargs):
print(args, kwargs)Two variables are defined: a list l = [1, 2, 3, 4] and a dictionary d = {"a": 1, "b": 2}.
First calling style test(l, d) Both l and d are placed into the args tuple, while kwargs remains empty, producing output similar to ([1, 2, 3, 4], {'a': 1, 'b': 2}) {}.
Second calling style test(*l, **d) The list is unpacked into positional arguments and the dictionary into keyword arguments, resulting in (1, 2, 3, 4) {'a': 1, 'b': 2}.
Next we examine a function that mixes a regular parameter with **kwargs:
def foo(action=None, **kwargs):
print("action", action, sep="=================>")
print("kwargs", kwargs, sep="=================>")Calling foo(d) passes the whole dictionary as the positional action argument, leaving kwargs empty. Calling foo(**d) unpacks the dictionary so that a=1 and b=2 become keyword arguments, while action stays None. The output screenshots illustrate these results:
Finally, a third call demonstrates a dictionary that also contains an action key:
d = {"action": "action", "a": 1}
foo(**d)The resulting output (shown in the second image) confirms that the action parameter receives the value from the dictionary, while the remaining items appear in kwargs:
Through these examples you should now understand how Python’s universal parameters work and how to choose the appropriate calling syntax.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
MaGe Linux Operations
Founded in 2009, MaGe Education is a top Chinese high‑end IT training brand. Its graduates earn 12K+ RMB salaries, and the school has trained tens of thousands of students. It offers high‑pay courses in Linux cloud operations, Python full‑stack, automation, data analysis, AI, and Go high‑concurrency architecture. Thanks to quality courses and a solid reputation, it has talent partnerships with numerous internet firms.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
