Packing and Unpacking Arguments in Python

Photo by Chris Ried on Unsplash

Intro

Let’s understand them one by one. Open your favorite code editor and just follow along.

Unpacking

# a function that takes 3 arguments
def fun(a,b,c):
print('{} {} {}'.format(a, b, c))
# list of arguments
a = ['Tom', '&', 'Jerry']
# passing the list
fun(a)

The output would be something like this:

Error: TypeError: fun() missing 2 required positional arguments: ‘b’ and ‘c’

Now, unpacking comes into play. We can use ∗(single asterisk) to unpack the list of arguments as shown below.

# a function that takes 3 argumentsdef fun(a,b,c):print('{} {} {}'.format(a, b, c))# list of arguments
myList = ['Tom', '&', 'Jerry']
# unpacking the list into 3 arguments
fun(*myList)

Output:

Tom & Jerry

Packing

# a function that uses packing to print unknown number of arguments
def friends(*names):
for name in names:
print(name)
friends('Tom')
friends('Tom', 'Jerry')

Output:

Tom

Tom

Jerry

Similarly, you can pack or unpack a dictionary of values by simply replacing ∗(single asterisk) with ∗∗(double asterisk).

Conclusion

  • Used in socket programming to send an infinite no. of requests to the server.
  • Used in the Django framework to send variable arguments to view functions.
  • There are wrapper functions that require us to pass in variable arguments.
  • Modification of arguments becomes easy but at the same time validation is not proper so they must be used with care.

Hope the article would have been helpful to you.

See you in the next one :-)

Hello World! I’m a Software Engineer. Loves toying the underlying structures of technologies in the world of zero’s and one’s.