Function for list and unpack list

I have two possible ways to call a function.

With a list:

some_list = [1,2,3,4]
my_function(some_list)

And with an unpacked list or a few arguments:

my_function(*some_list) == my_function(1,2,3,4)

which is equal to the first case:

my_function(some_list) == my_function(*some_list) == my_function(1,2,3,4)

In a function, my_functionI want to iterate over a list. Thus, for the frist case, the function looks like this:

def my_function(arg):
    for i in arg:
         # do something

Now for the second case, I repackaged the unpacked list, as a result we get the following function:

def my_function(*arg):
    for i in arg:
        # do something

Is there a way to have a good single function for both cases?

+4
source share
1 answer

You can create a wrapper authentication decorator for the wrapp function:

import functools


def autounpack(f):
  @functools.wraps(f)
  def wrapped(*args):
    if len(args) == 1 and type(args[0]) == list:
      return f(*args[0])
    else:
      return f(*args)
  return wrapped


@autounpack
def my_f(*args):
  print(args)

Here you have a living example.

+2
source

Source: https://habr.com/ru/post/1687215/


All Articles