0

I'm trying to make a list of methods and a list of parameters and find all possible matches that will not throw an error, but I can't figure out a way to make a function that can auto-input any number of parameters depending on the requirements of the function.

The code below is the closest I have gotten. I have looked into things like *args and **kwargs, but I need it to scale at the function call and not in the function. I worked a bit with a wrapper to the function but couldn't find a solution that was 100% automated.

    for f in self.functions:  # loop all functions
        for c in self.conditions:  # loop all conditions

            try:  # tries combination
                f(c)

            except TypeError as e: 

                for c2 in self.conditions:  

                    try: 
                        f(c, c2)

                    except TypeError as a:  

@staticmethod def test_method1(x): print("test_method1 = "+str(x))

@staticmethod
def test_method2(x, y):
    print("test_method2 = " + str(x)+" : "+str(y))

I would like a method that can give f() any number of parameters so the same method would be able to handle :

def test_method1(x):

def test_method2(x, y):

def test_method2(x, y, z):

and so on.

I'd also need to be able to save the function and the given parameters in an object like:

function = f
given_succesful_conditions = []
aschultz
  • 1,658
  • 3
  • 20
  • 30
Alex Skotner
  • 462
  • 1
  • 8
  • 18

1 Answers1

1

The correct approach is to use *args. It literally is intended to handle the case where you don't know how many arguments are being passed in.

You would use *args when you're not sure how many arguments might be passed to your function, i.e. it allows you pass an arbitrary number of arguments to your function. source

Example:

def test_method(*args):
    print(args)

test_method('x')
('x',)

test_method('x','y','z')
('x', 'y', 'z')

In the docs, it's referred to as 4.7.3. Arbitrary Argument Lists

Brennan
  • 504
  • 3
  • 14