Search code examples
pythonfunctiontuplesargs

Passing all elements of tuple in function 1 (from *args) into function 2 (as *args) in python


I am writing a function to take *args inputs, assess the data, then pass all inputs to the next appropriate function (align), also taking *args

*args seems to be a tuple. I have tried various ways of passing each element of the tuple into the next function, the latest two being:

            for x in args:
                align(*x)

and

            for x in args:
                align(args[0:len(args)])    

Solution

  • You "unpack them" with *args. Then the receiving function can mop them up into a tuple again (or not!).

    These examples should enlighten things:

    >>> def foo(*f_args):
    ...     print('foo', type(f_args), len(f_args), f_args)
    ...     bar(*f_args)
    ...     
    >>> def bar(*b_args):
    ...     print('bar', type(b_args), len(b_args), b_args)
    ...     
    >>> foo('a', 'b', 'c')
    ('foo', <type 'tuple'>, 3, ('a', 'b', 'c'))
    ('bar', <type 'tuple'>, 3, ('a', 'b', 'c'))
    

    Now, let's redefine bar and break the argspec:

    >>> def bar(arg1, arg2, arg3):
    ...     print('bar redefined', arg1, arg2, arg3)
    ...     
    >>> foo('a', 'b', 'c')
    ('foo', <type 'tuple'>, 3, ('a', 'b', 'c'))
    ('bar redefined', 'a', 'b', 'c')
    >>> foo('a', 'b')
    ('foo', <type 'tuple'>, 2, ('a', 'b'))
    ---> TypeError: bar() takes exactly 3 arguments (2 given)