-1

I'm trying to make a small function which calls another function from a library I import, I have 8 similar use cases but I don't want the code to be long and repeating.

each time I send the exact same function and with the same arguments but with different number of them.

Let me show an example of what I mean:

This is my function

def num_pack(num, 8_bytes):
    return struct.Struct(">Q Q Q Q Q Q Q Q").pack(num, num, num, num, num, num, num, num)

num is some generic counter, 8_bytes is a variable that runs from 1 to 8.

there are 8 possible options for the function that I use, it depends on the 8_bytes value. The number of Q in the string should be equal to the number of 8_bytes and the same goes for num.

The naive way to do it is :

    def num_pack(num, 8_bytes):
    if 8_bytes == 8:
        return struct.Struct(">Q Q Q Q Q Q Q Q").pack(num, num, num, num, num, num, num, num)
    if 8_bytes == 7:
        return struct.Struct(">Q Q Q Q Q Q Q").pack(num, num, num, num, num, num, num)
    if 8_bytes == 6:
        return struct.Struct(">Q Q Q Q Q Q").pack(num, num, num, num, num, num)
    .
    .
    .
    if 8_bytes == 1:
        return struct.Struct(">Q").pack(num)

I know how to modify the ">Q" string at each time by I don't know how to change the pack function's number of arguments.

I also know how to do this with eval, but this is bad practice and I don't want to use this method.

I'm sure there is some Pythonic way of doing so, Thanks in advance !

Dudu Gvili
  • 37
  • 6

1 Answers1

3

You can create a function that accepts any amount of arguments using the unpack operater *.

Here is an example of a function that takes any amount of arguments:


def my_awesome_function(*args):
   # do awesome job!
   print(args)

   # depending on len of args do something...

Or if you always have a one argument, but an unknown number of following arguments, you can formulate it like this:


def my_awesome_function(num, *all_other_args):
   # my number
   print(num)

   # do awesome job!
   print(all_other_args)

   # depending on len of args do something...

Here is full explanation of how to deal with unknown number of args, and more usefull operators: https://www.scaler.com/topics/python/packing-and-unpacking-in-python/

If you are looking to do it the other way around, such that a function deeds all the items in a list as separate arguments. This could be done like this with the * operator as well.

def foo(a, b, c):
    print(a, b, c)

values = ['adam', 'dave', 'elon']

# a valid funciton call would be
foo(*values)

# values  -> ['adam', 'dave', 'elon']
# *values -> 'adam', 'dave', 'elon'

Hopefully this helps. Please leave a comment if I misunderstood.

Good Luck!