Skip to content

Commit

Permalink
Safer try-except for catching infinite recursion
Browse files Browse the repository at this point in the history
  • Loading branch information
alvations committed Apr 19, 2016
1 parent 45d88b0 commit 2b7f2f5
Showing 1 changed file with 8 additions and 3 deletions.
11 changes: 8 additions & 3 deletions nltk/parse/generate.py
Expand Up @@ -36,6 +36,7 @@ def generate(grammar, start=None, depth=None, n=None):

return iter


def _generate_all(grammar, items, depth):
if items:
try:
Expand All @@ -44,12 +45,14 @@ def _generate_all(grammar, items, depth):
yield frag1 + frag2
except RuntimeError as _error:
if _error.message == "maximum recursion depth exceeded":
print("The grammar has rule(s) that yield infinite recursion!!\n", file=sys.stderr)
raise RuntimeError

# Helpful error message while still showing the recursion stack.
raise RuntimeError("The grammar has rule(s) that yield infinite recursion!!")
else:
raise
else:
yield []


def _generate_one(grammar, item, depth):
if depth > 0:
if isinstance(item, Nonterminal):
Expand All @@ -69,6 +72,7 @@ def _generate_one(grammar, item, depth):
P -> 'in' | 'with'
"""


def demo(N=23):
from nltk.grammar import CFG

Expand All @@ -78,5 +82,6 @@ def demo(N=23):
for n, sent in enumerate(generate(grammar, n=N), 1):
print('%3d. %s' % (n, ' '.join(sent)))


if __name__ == '__main__':
demo()

0 comments on commit 2b7f2f5

Please sign in to comment.