Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

filter_except() and map_except() #298

Merged
merged 2 commits into from Jul 19, 2019
Merged

filter_except() and map_except() #298

merged 2 commits into from Jul 19, 2019

Conversation

bbayles
Copy link
Collaborator

@bbayles bbayles commented Jul 16, 2019

This PR adds filter_except() and map_except().

filter_except() is like the built-in filter, but instead of skipping items that evaluate to False, it skips over items that raise a specific set of exceptions when validated. Here's an example using Django validators, which follow this pattern:

>>> from django.core.exceptions import ValidationError
... from django.core.validators import EmailValidator
... 
... from more_itertools import filter_except
... 
... 
... validator = EmailValidator()
... iterable = [
...     'good@example.com',
...     'good@localhost',
...     'bad',
...     'bad@bad_doman.com',
... ]
... list(filter_except(validator, iterable, ValidationError))
['good@example.com', 'good@localhost']

map_except() is like the built-in map(), but it skips over items that raise a specific set of exceptions when transformed.

>>> from django.core.exceptions import ValidationError
... from django.core.validators import EmailValidator
... 
... from more_itertools import map_except
... 
... 
... def extract_domains(address, validator=EmailValidator()):
...     validator(address)  # Raises if the address is invalid
...     return address.split('@')[1]
...     
... 
... iterable = [
...     'good@example.com',
...     'good@localhost',
...     'bad',
...     'bad@bad_doman.com',
... ]
... list(map_except(extract_domains, iterable, ValidationError))
['example.com', 'localhost']

@bbayles bbayles merged commit 64a3a4f into master Jul 19, 2019
@bbayles bbayles deleted the _except branch August 1, 2019 02:25
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

None yet

1 participant