Skip to content

Commit

Permalink
Merge pull request python-babel#289 from akx/allow-extract-callable
Browse files Browse the repository at this point in the history
Allow passing a callable to `extract()`
  • Loading branch information
sils committed Dec 20, 2015
2 parents 6b6546b + 3f58516 commit 2a51c9b
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 2 deletions.
8 changes: 6 additions & 2 deletions babel/messages/extract.py
Original file line number Diff line number Diff line change
Expand Up @@ -212,7 +212,8 @@ def extract(method, fileobj, keywords=DEFAULT_KEYWORDS, comment_tags=(),
... print message
(3, u'Hello, world!', [], None)
:param method: a string specifying the extraction method (.e.g. "python");
:param method: an extraction method (a callable), or
a string specifying the extraction method (.e.g. "python");
if this is a simple name, the extraction function will be
looked up by entry point; if it is an explicit reference
to a function (of the form ``package.module:funcname`` or
Expand All @@ -231,7 +232,9 @@ def extract(method, fileobj, keywords=DEFAULT_KEYWORDS, comment_tags=(),
:raise ValueError: if the extraction method is not registered
"""
func = None
if ':' in method or '.' in method:
if callable(method):
func = method
elif ':' in method or '.' in method:
if ':' not in method:
lastdot = method.rfind('.')
module, attrname = method[:lastdot], method[lastdot + 1:]
Expand All @@ -258,6 +261,7 @@ def extract(method, fileobj, keywords=DEFAULT_KEYWORDS, comment_tags=(),
'javascript': extract_javascript
}
func = builtin.get(method)

if func is None:
raise ValueError('Unknown extraction method %r' % method)

Expand Down
6 changes: 6 additions & 0 deletions tests/messages/test_extract.py
Original file line number Diff line number Diff line change
Expand Up @@ -546,3 +546,9 @@ def test_warn_if_empty_string_msgid_found_in_context_aware_extraction_method(sel
assert 'warning: Empty msgid.' in sys.stderr.getvalue()
finally:
sys.stderr = stderr

def test_extract_allows_callable(self):
def arbitrary_extractor(fileobj, keywords, comment_tags, options):
return [(1, None, (), ())]
for x in extract.extract(arbitrary_extractor, BytesIO(b"")):
assert x[0] == 1

0 comments on commit 2a51c9b

Please sign in to comment.