Skip to content

Instantly share code, notes, and snippets.

@gidgid
Last active April 19, 2023 11:18
Show Gist options
  • Save gidgid/623dcf440d83ffac01fa8e7ef04875bb to your computer and use it in GitHub Desktop.
Save gidgid/623dcf440d83ffac01fa8e7ef04875bb to your computer and use it in GitHub Desktop.
shows how to use the more_itertools partition function
from typing import Dict, Iterable, Set, Tuple
from more_itertools import partition
def process(
names: Iterable[str], whitelisted_names: Set[str], name_to_email: Dict[str, str]
) -> Tuple[Iterable[str], Iterable[str]]:
refused_names, approved_names = partition(
lambda name: name in whitelisted_names, names
) # 1
approved_emails = {name_to_email[name] for name in approved_names} # 2
return refused_names, approved_emails # 3
def test_only_return_emails_for_approved_users():
name_to_email = {"John": "john.doe@gmail.com", "Bob": "is.still.using@hotmail.com"}
names = {"Alice", "Bernard", "Bill"} | set(name_to_email.keys())
_, actual_emails = process(
names=names,
whitelisted_names=set(name_to_email.keys()),
name_to_email=name_to_email,
)
assert set(actual_emails) == set(name_to_email.values()) # 4
def test_filters_non_approved_users():
not_in_whitelist = {"Alice", "Bernard", "Bill"}
name_to_email = {"John": "john.doe@gmail.com", "Bob": "is.still.using@hotmail.com"}
names = not_in_whitelist | set(name_to_email.keys())
refused_names, _ = process(
names=names,
whitelisted_names=set(name_to_email.keys()),
name_to_email=name_to_email,
)
assert set(refused_names) == not_in_whitelist # 5
@420alan
Copy link

420alan commented Apr 19, 2023

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment