Skip to content

Commit

Permalink
Demonstrate about the generator issue for pre-3.3 version of Python.
Browse files Browse the repository at this point in the history
Signed-off-by: HE, Tao <sighingnow@gmail.com>
  • Loading branch information
sighingnow committed Jan 20, 2019
1 parent 8ed240e commit 63600d0
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 0 deletions.
5 changes: 5 additions & 0 deletions src/parsec/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -364,6 +364,11 @@ def desc(p, description):
# These parsers are applied successively and their results are sent back to the
# generator using `.send()` protocol. The generator should return the result or
# another parser, which is equivalent to applying it and returning its result.
#
# Note that `return` with arguments inside generator is not supported in Python 2.
# Instead, we can raise a `StopIteration` to return the result in Python 2.
#
# See #15 and `test_generate_raise` in tests/test_parsec.py
##########################################################################


Expand Down
22 changes: 22 additions & 0 deletions tests/test_parsec.py
Original file line number Diff line number Diff line change
Expand Up @@ -326,5 +326,27 @@ def xy():
# should not finish executing xy()
self.assertEqual(parser.parse('z'), 'z')

def test_generate_raise(self):

# `return` with argument inside generator is not supported in Python 2.
# Instead, we can raise a `StopIteration` directly with the intended
# result in generator for Python 2.
#
# Before Python 3.3, the `StopIteration` didn't have the `value` attribute,
# we need to assign the attribute manually.
#
# See #15.

@generate
def xy():
yield string('x')
yield string('y')
r = StopIteration('success')
r.value = 'success' # for pre-3.3 Python
raise r

parser = xy
self.assertEqual(parser.parse('xy'), 'success')

if __name__ == '__main__':
unittest.main()

0 comments on commit 63600d0

Please sign in to comment.