Francisco
Francisco

Reputation: 2228

Unknown variable for Python typehint

I have a wrapper function, what should I put as the return value if the variable to be returned is unknown?

def try_catch_in_loop(func_to_call: callable, *args):
    for attempt in range(NUM_RETRYS + 1):
        try:
            if attempt < NUM_RETRYS:
                return func_to_call(*args)
            else:
                raise RunTimeError("Err msg")
        except gspread.exceptions.APIError:
            request_limit_error()

Specifically looking what to put at the end of the function call ie:

def try_catch_in_loop(...) -> {What do I put here}:

Upvotes: 3

Views: 11640

Answers (2)

Patrick Haugh
Patrick Haugh

Reputation: 61032

By defining func_to_call to be a Callable that returns some Generic type, you can then say that try_catch_in_loop will also return that type. You would express this using a TypeVar:

from typing import Callable, TypeVar

return_type = TypeVar("return_type")

def try_catch_in_loop(func_to_call: Callable[..., return_type], *args) -> return_type:
    ...

Upvotes: 4

Francisco
Francisco

Reputation: 2228

Looks like you can use the Any type. https://docs.python.org/3/library/typing.html#typing.Any

Upvotes: 0

Related Questions