Packing and Unpacking Arguments in Python

Python Methods and Functions

Background
Consider a situation where we have a function that takes four arguments. We want to make a call to this function, and we have a list of size 4 that has all the arguments for the function. If we just pass the list to the function, the call won't work.

# Python program to demonstrate the need
# packing and unpacking

  
# An example of a function that takes 4 arguments
# and prints them.

def fun (a, b, c, d):

  print (a, b, c, d)

 
Driver code

my_list = [ 1 , 2 , 3 , 4 ]

 
# This doesn't work
fun (my_list)

Output:

 TypeError: fun () takes exactly 4 arguments (1 given) 

Unpack
We can use *, to unpack the list so that all of its elements can be passed as different parameters.

Output:

 (1, 2, 3, 4) 

As another example, consider the built-in function range ( ), which expects separate start and stop arguments. If they are not available separately, write a function call with the * operator to unpack arguments from a list or tuple:

# An example of a function that takes 4 arguments
# and prints,

def fun (a, b, c, d):

print (a, b, c, d) 

 
Driver code

my_list = [ 1 , 2 , 3 , 4 ]

 
# Unpack the list into four arguments

fun ( * my_list)

& gt; & gt; & gt; 

& gt; & gt; & gt;  range ( 3 , 6 # normal call with separate arguments

[ 3 , 4 , 5 ]

& gt; & gt; & gt; args = [ 3 , 6 ]

& gt; & gt; & gt;  range ( * args)  # call with arguments unpacked from the list

[ 3 , 4 , 5 ]

packing
When we don't know how many arguments to pass to a python function, we can use Packing to pack all the arguments into a tuple.

# Python program to demonstrate usage
Package #

 
# This function uses wrapping to sum
# unknown number of arguments

def mySum ( * args):

sum = 0

for i in range ( 0 , len (args)):

sum = sum + args [i]

return sum  

  
# Driver code

print (mySum ( 1 , 2 , 3 , 4 , 5 ))

print (mySum ( 10 , 20 ))

Output:

 15 30 

The above mySum () function does "boxing" to wrap all the arguments this method call receives into one variable. Once we have this "packed" variable, we can do with it what we do with a regular tuple. args [0] and args [1] will give you the first and second arguments, respectively. Since our tuples are immutable, you can convert the args tuple to a list so you can also modify, delete, and reorder the elements in i.

Packing and Unpacking
Below is an example which shows both boxing and unboxing.

# Python program to demonstrate both packaging and
# unpack.

 
# An example Python function that accepts three arguments
# and prints them

def fun1 (a, b, c):

print (a, b, c)

 
# One more for an example function.
# This is an example of PACKING. All arguments passed
# to fun2 are packed in * args tuples.

def fun2 ( * args):

 

# Convert the args tuple to a list to we could change it

args = list (args)

 

# Change arguments

args [ 0 ] = 'Geeksforgeeks'

  args [ 1 ] = 'awesome'

  

# UNPACKING the arguments and calling fun1 ()

fun1 ( * args)

 
# Driver code

fun2 ( 'Hello' , ' beautiful' , ' world! ' )

Output:

 (Geeksforgeeks, awesome, world!) 

** used for dictionaries

 
# Sample program to demonstrate unpacking
# dictionary elements using **

def fun (a, b, c):

print (a, b, c)

 
# Call with dictionary unpacking

d = { 'a' : 2 , ' b' : 4 , 'c' : 10 }

fun ( * * d)

Exit-

 2 4 10 

Here ** unpacked the dictionary used with it and passed the items in the dictionary as keyword arguments to function. Thus, writing "fun (1, ** d)" was equivalent to writing "fun (1, b = 4, c = 10)".

# Python package demonstration program
# dictionary elements using **

def fun ( * * kwargs):

 

# Kwargs is a dictate

print ( type (kwargs))

 

# Print dictionary items

  for key in kwargs:

print ( "% s =% s" % (key, kwargs [key]))

 
# Driver code

fun (name = "geeks" , ID = " 101 " , language = " Python " )

Output:

 & lt; class 'dict' & gt; language = Python name = geeks ID = 101 

Applications and Highlights
1. Used in socket programming to send a huge number of requests to the server. 
2. Used in the Django framework to send variable arguments to view functions. 
3. There are wrapper functions that require us to pass variable arguments. 
4. Modifying the arguments becomes easy, but at the same time the validation is not correct, so they should be used with caution.


Reference:

http://hangar.runway7.net/python/packing-unpacking-arguments

This article is contributing to Shwetanshu Rohatgi If you love Python.Engineering and would like to contribute, you can also write an article using contribute. python.engineering or by posting to [email protected] See your article appearing on the Python.Engineering homepage and help other geeks.

Please post comments if you find anything wrong or if you'd like to share more information on the topic under discussion





Get Solution for free from DataCamp guru