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

Add allow_key decorator to accept object #278

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
12 changes: 12 additions & 0 deletions fuzzywuzzy/utils.py
Expand Up @@ -99,6 +99,18 @@ def full_process(s, force_ascii=False):
string_out = StringProcessor.strip(string_out)
return string_out

def allow_key(func):
"""Allow key function that extracts the text from passed object to be used.
similar to python's max, min functions
"""
@functools.wraps(func)
def decorated(*args,
key = lambda s: s, #type: Callable[[Any], str]
**kwargs):
kwargs.update(zip(func.__code__.co_varnames, args))
return func(**{k:key(v) for k,v in kwargs.items()})
return decorated


def intr(n):
'''Returns a correctly rounded integer'''
Expand Down
17 changes: 17 additions & 0 deletions test_fuzzywuzzy.py
Expand Up @@ -4,6 +4,7 @@
import re
import sys
import pycodestyle
from collections import namedtuple

from fuzzywuzzy import fuzz
from fuzzywuzzy import process
Expand Down Expand Up @@ -50,6 +51,9 @@ def setUp(self):
"a\xac\u1234\u20ac\U00008000",
"\u00C1"
]
self.Dummy = namedtuple("DummyObject",["content"])
self.dummy_key_simple = lambda obj:obj.content
self.dummy_key_typed = lambda obj:obj.content if isinstance(obj,self.Dummy) else obj

def tearDown(self):
pass
Expand All @@ -72,6 +76,19 @@ def test_fullProcessForceAscii(self):
for s in self.mixed_strings:
utils.full_process(s, force_ascii=True)

def testAllowKey(self):
s1_obj = self.Dummy(self.s1)
@utils.allow_key
def upper(s): return s.upper()
self.assertEqual(self.s1.upper(), upper(s1_obj, key=self.dummy_key_simple))
@utils.allow_key
def upper_if_length_n(s, length):
if len(s) == length: return s.upper()
else: return s
processed = upper_if_length_n(s1_obj, length=len(self.s1),
key=self.dummy_key_typed)
self.assertEqual(self.s1.upper(), processed)


class RatioTest(unittest.TestCase):

Expand Down