Search code examples
pythonfunctionargumentsargs

Calling a function within a function and passing its arguments (*args) - Python


I don't see myself that bad in python but I am struggling to figure out what it is wrong in my code.

import numpy as np

x = np.array([[1, 2], [3, 4]])

def func1(x, params, *args):
    x = x.T
    if args[0] == 'condition':
        params['parameter1'] = False
        args = args[1:]
    else:
        params['parameter1'] = True
    return x, params

def func2(x, *args):
    params = {}
    params['parameter1'] = True
    params['parameter2'] = 'solid'
    params['parameter3'] = 200
    x, params = func1(x, params, args[:])
    print(params)
    print(x)
    print(args)

func2(x, 'condition')

The problem I am facing is that the "if" in func1 is not executed. Python does not see that args[0] is equal to the string 'condition' despite that I clearly pass it when calling the func2 on the last line. Despite that we I print the length of args before If-statement, I get 1 as an indication that there is indeed an argument "condition" being passed.

print(len(args)) *# gives 1*

I will appreciate your feedback. Thank you in advance.


Solution

  • Try replacing

    x, params = func1(x, params, args[:])
    

    with

    x, params = func1(x, params, *args)
    

    If you do not use the * the value that is stored in args in func1 will be (('condition',),) instead of ('condition',). Thats also why print(len(args)) still gives one as output.