variable argument unpacking

Peter Otten __peter__ at web.de
Mon May 23 06:53:37 EDT 2016


Mehrzad Irani wrote:

> 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.

Python 3 allows

$ cat b.py
def a(*d, a=1, b=2, c=3, **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)
$ python3 b.py
1 2 3
()
{'e': 7, 'f': 8, 'g': 9}
1 2 3
(3,)
{'e': 7, 'f': 8, 'g': 9}
1 2 3
(3, 2, 1, 4, 5, 6)
{'e': 7, 'f': 8, 'g': 9}
1 2 3
(4, 5, 6)
{'e': 7, 'f': 8, 'g': 9}
1 2 3
(4, 5, 6, 7)
{'e': 7, 'f': 8, 'g': 9}

Perhaps that is more to your liking? I find the output as unreadable as of 
your a.py, so I won't bother to check...




More information about the Python-list mailing list