1

Is it possible to pass an unknown amount of variables, via a single variable, into a function call?

The issue I am having is that I am iterating over a dataframe and each row will use a bitstring pack function call - each call might have a different number of arguments depending on the length of a list in row['Data']

for index, row in log_file.iterrows():
    pack_string = 'u1u11u1u1u1u4{}'.format('u8'*len(row['Data']))
    packed = bitstruct.pack(pack_string, 0, row['ID'], 0, 0, 0, len(row['Data']),)

Examples of pack_string might look like this:

u1u11u1u1u1u4u8u8u8
u1u11u1u1u1u4u8u8u8u8u8u8
u1u11u1u1u1u4u8u8
u1u11u1u1u1u4u8u8u8u8u8u8u8u8

For every u8 I need to pass a new variable into the bitstruct.pack() method. So for a single loop on the pack_string u1u11u1u1u1u4u8u8 the solution would be:

pack_string = 'u1u11u1u1u1u4{}'.format('u8'*len(row['Data']))
packed = bitstruct.pack(pack_string, 0, row['ID'], 0, 0, 0, len(row['Data']), row['Data'][0], row['Data'][1])

An ideal solution for a chaning number of parameters might look something like this:

for index, row in log_file.iterrows():
    pack_string = 'u1u11u1u1u1u4{}'.format('u8'*len(row['Data']))
    *args = row['Data']
    packed = bitstruct.pack(pack_string, 0, row['ID'], 0, 0, 0, len(row['Data']), *args)
RMRiver
  • 625
  • 1
  • 5
  • 19

1 Answers1

1

You can unpack am arbitrary iterable into individual arguments using the "splat" operator:

for index, row in log_file.iterrows():
    pack_string = 'u1u11u1u1u1u4{}'.format('u8'*len(row['Data']))
    packed = bitstruct.pack(pack_string, 0, row['ID'], 0, 0, 0, len(row['Data']), *row['Data'])

The only issue with your last attempt is that *args = row['Data'] should have been just

args = row['Data']
Mad Physicist
  • 107,652
  • 25
  • 181
  • 264