Partial functions in Python with partial from functools


Python tip:

You can use partial from functools to freeze a certain number of arguments from a function and create a new, simplified function.

It returns a new partial object which when called will behave like a function called with the positional args and keywords.

An example 👇

from functools import partial

all_users = [
    {"email": "[email protected]"},
    {"email": "[email protected]"},
    {"email": "[email protected]"},
]


def _sort_users_by_email(users, sort_order):
    asc_dsc_to_reverse = {
        "ascending": True,
        "descending": False,
    }

    return sorted(
        users, key=lambda user: user["email"], reverse=asc_dsc_to_reverse[sort_order]
    )


_sort_users_by_email_ascending = partial(_sort_users_by_email, sort_order="ascending")
_sort_users_by_email_descending = partial(_sort_users_by_email, sort_order="descending")


print(_sort_users_by_email_ascending(all_users))
# [{'email': '[email protected]'}, {'email': '[email protected]'}, {'email': '[email protected]'}]

print(_sort_users_by_email_descending(all_users))
# [{'email': '[email protected]'}, {'email': '[email protected]'}, {'email': '[email protected]'}]