Wednesday, July 16, 2014

50. Argument Packing and Unpacking

Argument packing, and unpacking, is common in Python and especially, in Kivy.




The print function is imported from __future__ module for Python 3 compatibility. A function calc1() has 3 arguments.




The function calc2() and calc3() are almost identical. Because of the * symbol, args will pack the arguments it receives into a tuple. In calc2(), we use the individual elements to define the local variables a, b, and c. In calc3(), we use unpacking of args to three local variables.




In the main code, the same arguments are used for calc1(), calc2(), and calc3(). The results are placed in val1, val2, and val3. We know they should be the same.




If we have a list, or tuple with the parameters, the * symbol may be used to unpack – that is, if we have a 3-length list, it becomes 3 variables. If we did not use a * symbol, Python would have complained about not finding 3 arguments.


# ex50.py

from __future__ import print_function

def calc1(a,b,c):
    return 2*a+3*b+4*c

def calc2(*args):
    a = args[0]
    b = args[1]
    c = args[2]
    return 2*a+3*b+4*c

def calc3(*args):
    a,b,c = args
    return 2*a+3*b+4*c

def on_touch_down(self,*args):
    touch,res = args
    print(touch)
    print(res)

    
if __name__=='__main__':
    val1 = calc1(1,2,3)
    print('val1 =',val1)
    val2 = calc2(1,2,3)
    print('val2 =',val2)
    val3 = calc3(1,2,3)
    print('val3 =',val3)
    in1 = 1,2,3
    val4 = calc1(*in1)
    print('val4 =',val4)
    on_touch_down(1,1)


    



The result shows that val1 to val4 are equal, with a value of 20. For parameters with names, we can also have dictionary packing and unpacking.




We can always use *args, in function definitions. For example, for on_touch_down we can use *args to convert the argument into a tuple. However, that tuple will only have one element. *args is usually used if you have many arguments, or even if you have a variable number of arguments.




3 comments:

  1. Python:

    Good Post! Thank you so much for sharing this pretty post, it was so good to read and useful to improve my knowledge as updated one, keep blogging.

    https://www.emexotechnologies.com/online-courses/python-training-in-electronic-city/

    ReplyDelete
  2. Good Post! Thank you so much for sharing this pretty post, it was so good to read and useful to improve my knowledge as updated one, keep blogging.

    Python Training in electronic city

    ReplyDelete