[go: up one dir, main page]

DEV Community

Cover image for *args and *kwargs, ARG! 🏴‍☠️
Richard
Richard

Posted on

*args and *kwargs, ARG! 🏴‍☠️

Most people learn about *args and **kwargs while learning Python without really understanding what's going on.

Functions have arguments. Here's a basic function that prints passed arguments.

def printArgs(first, second):
  print(first)
  print(second)

//invoke it
printArgs(1, 2)

//this will print:
1
2
Enter fullscreen mode Exit fullscreen mode

Well, that's cool I guess. But what if you have a case where you are not sure how many arguments will be passed? This function prints two. What if there's one?
TypeError: printArgs() takes exactly 2 arguments...
What if there are three? Or fifty? It'll only print two.

Here's where *args come in.

def printingArgs(*args):
  for arg in args:
    print(arg)

//invoke it
printingArgs(1, 2, 3, 4)

//prints
1
2
3
4
Enter fullscreen mode Exit fullscreen mode

Note: You can name *args whatever you want. It's the * at the beginning that makes it count. You can name it *asdf and then use

for thing in asdf:
   print(thing)
Enter fullscreen mode Exit fullscreen mode

and it will still work.

*kwargs are similar, but they mean Keyword Args; that is, arguments named with keywords like firstName="Bob" or something.

def printingArgsAndKwargs(*args, **kwargs):
  for arg in args:
    print(arg)
  for key, value in kwargs.items():
    print(key,value)

//invoke it
printingArgsAndKwargs(1, 2, 3, a=1, b=2, c=3)

//prints args first
1
2
3
//prints kwargs
('a', 1)
('b', 2)
('c', 3)
Enter fullscreen mode Exit fullscreen mode

And there you are, as simple as possible.

Top comments (0)