Python list like * args?

I have two Python functions, each of which takes variable arguments in its function definitions. To give a simple example:

def func1(*args):
    for arg in args:
        print arg

def func2(*args):
    return [2 * arg for arg in args]

I would like to compose them - as in func1(func2(3, 4, 5))- but I do not want argsto func1was ([6, 7, 8],), I want it to be (6, 7, 8)as if it was named func1(6, 7, 8), and not func1([6, 7, 8]).

Normally I would simply use func1(*func2(3, 4, 5))or have func1to check if there was a args[0]list. Unfortunately, I can’t use the first solution in this particular instance, and to apply the second one I will need to perform such a check in many places ( func1there are many functions in the role ).

Does anyone have any ideas how to do this? I suppose some kind of introspection might be used, but I could be wrong.

+3
source share
3 answers

You can use Decorator as published by Yaroslav.

Minimal example:

def unpack_args(func):
    def deco_func(*args):
        if isinstance(args, tuple):
            args = args[0]

        return func(*args)

    return deco_func


def func1(*args):
    return args

def func2(*args):
    return args

@unpack_args
def func3(*args):
    return args

print func1(1,2,3)    # > (1,2,3)
print func2(1,2,3)    # > (1,2,3)
print func1(*func2(1,2,3))    # > (1,2,3)
print func1(func2(1,2,3))    # > ( (1,2,3), )
print func3(func2(1,2,3))   # > (1,2,3)
+3
source

You might consider creating a function decorator that checks if the first argument is a list. Applying a decorator to existing functions is a bit simpler than changing functions.

+4
source

func1(*func2(3, 4, 5)) func1, , args[0] list. , , ​​ ( func1 ).

?

>>> def func1(*args):
    for arg in args:
        print arg

>>> def func2(*args):
    return [2 * arg for arg in args]

>>> func2(3, 4, 5)
[6, 8, 10]
>>> func1(1,2,3)
1
2
3
>>> func1(*func2(3, 4, 5))
6
8
10
>>> 

, func1(*tuple(func2(3, 4, 5))) ( ).

+1
source

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


All Articles