variable argument unpacking

Mehrzad Irani i.mehrzad at gmail.com
Mon May 23 06:27:50 EDT 2016


Hi All,

Consider the situation
[cti at iranim-rhel python_cti]$ cat a.py
def a(a = 1, b = 2, c = 3, *d, **e):
        print(a, b, c)
        print(d)
        print(e)

r = {'e': 7, 'f': 8, 'g': 9}


a(**r)
a(3, **r)

r1 = (4,5,6)

a(3,2,1,*r1, **r)
a(*r1, **r)

r1 = (4,5,6,7)
a(*r1, **r)

[cti at iranim-rhel python_cti]$

The output for this program is as follows:
[cti at iranim-rhel python_cti]$ python a.py
(1, 2, 3)
()
{'e': 7, 'g': 9, 'f': 8}
------------------
(3, 2, 3)
()
{'e': 7, 'g': 9, 'f': 8}
------------------
(3, 2, 1)
(4, 5, 6)
{'e': 7, 'g': 9, 'f': 8}
------------------
(4, 5, 6)
()
{'e': 7, 'g': 9, 'f': 8}
------------------
(4, 5, 6)
(7,)
{'e': 7, 'g': 9, 'f': 8}

This program shows, that for d to get assigned, I would need to first assign a, b, c even though their default parameters have been set.

Also, if I would like to unpack a, b, c using e; I would get a multiple assignment TypeError.

Therefore, my question is - is there a way to assign d, without going through the assignments of a, b, c again, since they have already been assigned defaults? (I think I am missing something simple here)

Thanks in advance.



More information about the Python-list mailing list