I want to annotate my function using type hints. I am running into a problem where I am using a function as input parameters (or more specifically, a class-method), and I do not know how I should define the type hint. The code is as follows:
async def get_mails(api: SomeApi,
all_contacts: ContactDict,
query_function: ???,
aggregate_function: ???) -> list:
customer_emails = await query_function()
for customer_email in customer_emails:
for email in await get_emails_by_customer(api, customer_email, get_employees()):
all_contacts[customer_email].add_mail(email)
return aggregate_function()
I added ??? Where I want to add the type hint for the functions.
CodePudding user response:
I think what you are looking for is the Callable
type. More info from the python docs here
Importantly, from the docs:
The subscription syntax must always be used with exactly two values: the argument list and the return type. The argument list must be a list of types or an ellipsis; the return type must be a single type.
So, for example, your function definition for get_mails
might look like something like:
from typing import Callable
async def get_mails(api: SomeApi,
all_contacts: ContactDict,
query_function: Callable[[list, of, input, types], output_type],
aggregate_function: Callable[[list, of, input, types], output_type]) -> list:
...
Alternatively, you can use a plain Callable
, which is equivalent to Callable[..., Any]
.