Last active
August 29, 2015 14:10
-
-
Save abg/7813c54d173e1631219c to your computer and use it in GitHub Desktop.
inclusion/exclusion filter implementation
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
import fnmatch | |
def inclusion_exclusion_filter(include=(), exclude=()): | |
"""Create an inclusion exclusion filter | |
:param include: sequence of glob patterns to include | |
:param exclude: sequence of glob patterns to exclude | |
:returns: function(name) that filters strings based on the provided filters | |
""" | |
def apply_filter(name): | |
"""Apply a filter to ``name`` | |
If inclusion patterns are specified and no patterns are | |
matched, the value will be excluded and this function | |
returns ``True``. | |
If no inclusion patterns are specified all values will | |
be included unless some exclusion pattern is matched. | |
If an exclusion pattern is matched, the matched pattern | |
will be returned as true value. | |
If no exclusion patterns were matched, ``False`` is returned | |
indicating the value was not excluded | |
:param name: string value to filter | |
:returns: true value if filtered, False otherwise | |
""" | |
if include: | |
for pattern in include: | |
if fnmatch.fnmatch(name, pattern): | |
break | |
else: | |
# no exclusion patterns matched | |
return True | |
for pattern in exclude: | |
if fnmatch.fnmatch(name, pattern): | |
return pattern | |
return False | |
return apply_filter | |
if __name__ == '__main__': | |
pred = inclusion_exclusion_filter(include=['mysql.*'], exclude=['mysql.proc*']) | |
assert pred('mysql.user') is False | |
assert pred('mysql.proc') == 'mysql.proc*' |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment