Packing and Unpacking Arguments in Python

Photo by Chris Ried on Unsplash

Intro

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)
# 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)

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')
Tom

Tom

Jerry

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.