billypilgrim
billypilgrim

Reputation: 145

Method that takes a method as a parameter with an optional parameter

I have two methods from a library that work in the same manner. The difference is that one takes an additional, optional parameter. For example:

def method1(a, b, c):
    ...

def method2(a, b, c, d=None):
    ...

I have to perform the same task on the results of these methods, so I have a method that combines them that looks like this:

def wrapper(method, a, b, c, d=None):

    ...

    if d:
        results = method(a, b, c, d=d)
    else:
        results = method(a, b, c)

    ...

This works, but as I add more methods that have different optional arguments it becomes cumbersome. Is there a way a better way to handle these parameters?

Upvotes: 1

Views: 70

Answers (2)

billypilgrim
billypilgrim

Reputation: 145

For the wrapper function, I decided to just do something like the following as suggested in the comments:

def wrapper(method, *args):

    ...

    results = method(*args)

    ...

Error handling should be incorporated to make sure the proper arguments are being passed as well, as suggested in another answer.

Upvotes: 0

dmmfll
dmmfll

Reputation: 2836

Here is some code that might accomplish what you're looking for.

You can pass a collection of methods into wrapper and that function will return the value of any method that has key word arguments mapped to kwargs.

def method1(a, b, c):
    return a, b, c


def method2(a, b, c, d=None):
    return a, b, c, d

methods = (
    method1,
    method2,
) # Collection of methods to run.

def wrapper(kwargs, methods=methods):
    """Loop over methods with kwargs."""
    for method in methods:
        try: # Call method with **kwargs
            return method(**kwargs) # Return value if keys in kwargs fit signature of method.
        except TypeError as err: # Handle error if keyword args don't match.
            print(f'err "{err}" for method "{method}')

kwargs_collection = (dict(zip(args, (f'value for arg: "{arg}"' for arg in args)))
                     for args in ('abcd', 'abc', ))




for test_kwargs in kwargs_collection:
    print(wrapper(test_kwargs))

OUTPUT:

err "method1() got an unexpected keyword argument 'd'" for method "function method1 at 0x7f900c2b7d90"

('value for arg: "a"', 'value for arg: "b"', 'value for arg: "c"', 'value for arg: "d"')

('value for arg: "a"', 'value for arg: "b"', 'value for arg: "c"')

Upvotes: 1

Related Questions