Search code examples
pythontimedelegateswait

python - Generic function that accept another function as parameter and wait until condition


So I have this function` that gets my user status from the database:

def get_status(user_name: str) -> str:
    # connect to db.
    user = ...
    return user.status

Now I have to wait maximum time until my user status will be connected (it could take up to several minutes):

def wait_until_user_status(user: str, timeout: int)
    status = get_status(user)
    start = time.time()
    while time.time() - start < timeout and status != `connected`:
        time.sleep(2)
        status = get_status(user)
   if status != `connected`:
       raise Exception(f'Timeout of {timeout} seconds reached')

Usage:

try:
    wait_for('bil', 120)
except Exception as ex:
    print(ex)

So my question is: In case I have several function that I want to verify something inside (In the above example - user status) is it possible to declare a generic function that accepts another function and wait until timeout? (In my example - send function that return status and wait until some condition).

For example:

def generic_wait(timeout: int, function):
    pass

Usage:

generic_wait(timeout=120, function=wait_until_user_status(user='bil', status='connected')

Solution

  • Yes, you can make this function generic by passing the function in arguments. Please check the below code for better understanding.

    def func1(arg1, arg2):
        print(f"I am {arg1} & I am {arg2}")
    
    def call_me(func1, args):
        func1(**args)
    
    call_me(func1, {"arg1": 10, "arg2": 20})
    
    Output: I am 10 & I am 20
    

    You can pass the function func1 with its arguments as dict inside the call_me function and unpack that with ** into keyword arguments.