Last active
August 29, 2015 14:07
-
-
Save karthikbgl/59492568c9ead3eed448 to your computer and use it in GitHub Desktop.
Usage of partials
This file contains 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
''' | |
This is an example of functools.partials | |
Typical usage is when you have a function that needs multiple parameters, | |
of which one is a constant, you can use a partial. | |
Example: | |
Return only the values in an iterable which match the regex 'c.t' where . is a single character. | |
Input: | |
['cat', 'cut', 'abc', 'def'] | |
Output: | |
['cat', 'cut'] | |
''' | |
import re | |
import functools | |
def re_match(pattern, val): | |
return True if re.match(pattern, val) else False | |
def match_filter(arr, pattern): | |
if not arr: | |
return None | |
re_match_partial = functools.partial(re_match, pattern) | |
x = filter(re_match_partial, arr) | |
print x | |
match_filter(['cat', 'cut', 'abc', 'def'], 'c.t') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment