Skip to content

Instantly share code, notes, and snippets.

@karthikbgl
Last active August 29, 2015 14:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save karthikbgl/59492568c9ead3eed448 to your computer and use it in GitHub Desktop.
Save karthikbgl/59492568c9ead3eed448 to your computer and use it in GitHub Desktop.
Usage of partials
'''
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