BlueCompany
BlueCompany

Reputation: 72

Invoke any method with unknown amount of variables from another method

Here is my code:

import time

def f(method,timeout,condition=False,*args,**kwargs):
    t_end=time.time() +timeout
    while time.time()<t_end:
        ret=method(*args,**kwargs)
        if condition:
            return ret
    return ret

def f2(a,b):
    print(a,b)
def f3(a):
    print(a)

The question is: how to invoke method f so it can work with arguments f2 and f3 eg. f(f2,2,*(1,2)) And I don't want to use @decorator.

Upvotes: 0

Views: 28

Answers (1)

Ramkishore M
Ramkishore M

Reputation: 389

condition=False is a keyword argument. So move it next to *args. Other than that, just pass arguments depending on the function you pass.

import time

def f(method, timeout, *args, condition=False, **kwargs):
    t_end = time.time() + timeout
    while time.time() < t_end:
        ret = method(*args,**kwargs)
        if condition:
            return ret
    return ret

def f2(a, b):
    print(a, b)
def f3(a):
    print(a)

f(f2, 2, *(1,2))
f(f3, 2, 1)

Upvotes: 1

Related Questions