variable argument unpacking
Veek M
vek.m1234 at gmail.com
Mon Dec 5 00:43:27 EST 2016
Peter Otten wrote:
> 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...
import inspect, linecache
def a(a = 1, b = 2, c = 3, l = 0, *d, **e):
lineno = inspect.currentframe().f_back.f_lineno
print 'line', lineno, linecache.getline(__file__, lineno),\
linecache.getline(__file__, lineno-1)
print(a, b, c)
print(d)
print(e)
print '----------------'
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)
(thanks to erica on freenode who linked me to:
http://code.activestate.com/recipes/145297-grabbing-the-current-line-number-easily/)
More information about the Python-list
mailing list