Another question about variable args.

Neil Cerutti horpner at
Tue Aug 7 19:42:20 CEST 2007

On 2007-08-07, Steven W. Orr <steveo at> wrote:
> I have a structure I need to pack. I call struct.pack about a dozen times 
> and each call takes about 53 arguments.
> I create a sequence of the arguments:
> a1 = 1
> a2 = 2
> a3 = 3
> etc...
> a54 = 88
> myseq = (a1, a2, a3, a4 etc... a53)
> Also I made
> def mpack ( fmt, *ss ):
>      print type(ss)
>      for ii in ss:
>          print 'ii = ', ii, 'type(ii) = ', type(ii)
>      for ii in list(ss):
>          print 'ii = ', ii, 'type(ii) = ', type(ii)
>      return struct.pack(fmt, *ss )
> In my main, this first print statement works.
> print 'main:', mpack(ff, a, b, c, d, e, f, g, h, i)
> 1. For the life of me, I can't figure out what to do to get the
> next print to work. The idea is that I want to make my code
> clearer by not passing 50+ args each time and to instead pass a
> sequence which when evaluated will be the desired list of args.
> print 'main:', mpack(ff, subseq)
> 2. And then, if possible, I'd like to do it in such a way that
> one myseq is defined, its value can automagically be re-eval'd
> so I don't have to re-assign to myseq each time one of the 50+
> variables changes prior to calling pack.

A functor might be a fun solution.

class mpack_maker(object):
  def __init__(self, fmt, *args):
    self.fmt = fmt
    self.arg_list = list(args)
  def __call__(self, slice=None, subseq=None):
    if slice:
      self.arg_list[slice] = subseq
    return struct.pack(self.fmt, *self.arg_list)

You can pass in a slice object and a subsequence to change
arguments (permanently).

>>> mpack = mpack_maker(ff, a, b, c, d, e, f, g, h)
>>> mpack() # Call the function
>>> mpack(slice(5, 7), [0, 7]) # Change args 5 and 6, and call again.

The args you can change are limited by the slicing powers of
Python, and probably combining arg-changing with calling the
function isn't wise, but that's a sketch anyhow.

Neil Cerutti
We couldn't beat... us.  We couldn't even beat us.  I was trying to think of
somebody bad, and I couldn't think of anybody else.  Us. --Tim Legler

More information about the Python-list mailing list