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 !