Detailed explanation of Python's powerful variable parameter delivery mechanism

  • 2021-06-28 13:04:12
  • OfStack

Simulate and define map functions today. Write to find out how flexible and powerful Python variable length parameters are.

Suppose there is a tuple, t, with n members:


t=(arg1,...,argn)

One function, f, accepts exactly n parameters:


f(arg1,...,argn)

f (t) is obviously wrong, so how to pass each member of t as an independent parameter to f in order to achieve the effect of f (arg1,..., argn) ?

I started with a very original solution, which first converted the t members into strings, then concatenated them with English commas to form a "standard parameter string":


str_t=(str(x) for x in t)
str_args=",".join(str_t)

str_args becomes the string "arg1,..., argn", and so on,


eval('%s(%s)'%(f.__name__,str_args))

It looks like:


f(arg1,...,argn)

Old version:


def imap(func,arr,*arrs):
 allarrs=(arr,)+arrs
 args=[]
 for i in range(len(arr)):
  member=[]
  for ar in allarrs:
   member.append(str(ar[i]))
  args.append(member)
 return (eval('%s(%s)'%(func.__name__,','.join(member))) for member in args)

print list(imap(float,(1,2,3,4)))
print list(imap((lambda x,y,z:x+y+z),(1,1,1,1),(1,1,1,1),(1,1,1,1)))

1 Running found that the named function float works well, but not the anonymous function lambda. Obviously, the limitation of the eval idea is here.

It suddenly occurred to me that direct f (*t) would do the trick!Thus, the new version:


def imap(func,arr,*arrs):
 allarrs=(arr,)+arrs
 return (func(*(ar[i] for ar in allarrs)) for i in range(len(arr)))

print list(imap(float,(1,2,3,4)))
print list(imap((lambda x,y,z:x+y+z),(1,1,1,1),(1,1,1,1),(1,1,1,1)))

Result:


>>> 
[1.0, 2.0, 3.0, 4.0]
[3, 3, 3, 3]

And function (*args_The powerful mechanism of tuple is that args_tuple 1 is not necessarily a tuple. Any Iterable object can be. List, Dictionary, Generator, etc.


>>> def function(*iterable):
 print iterable

 
>>> function(*(1,2,3))
(1, 2, 3)
>>> function(*[1,2,3])
(1, 2, 3)
>>> function(*{1:'',2:''})
(1, 2)
>>> function(*(i for i in range(4)))
(0, 1, 2, 3)
>>>

Related articles: