Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Python typing: how to define a function or method?

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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].

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading