How to get rid of warning "DeprecationWarning generator 'ngrams' raised StopIteration"
Asked Answered
K

3

11

While working on a Kaggle notebook I ran into an issue. The following code block:

from nltk import ngrams
def grams(tokens):
    return list(ngrams(tokens, 3))
negative_grams = preprocessed_negative_tweets.apply(grams)

resulted in a red box appearing saying

/opt/conda/bin/ipython:5: DeprecationWarning: generator 'ngrams' raised StopIteration

The variable preprocessed_negative_tweets is a Pandas data frame containing tokens.

Anyone know how to make this go away?

(Full notebook available here)

Keefe answered 25/4, 2017 at 17:33 Comment(2)
The cause of the warning is the change in behavior described in PEP 479. How to best make it go away I can't say exactly, but you may need to just filter and ignore the DeprecationWarning...Ellerey
Quick question. Which nltk version are you using? Also which Python version are you using?Lorrainelorrayne
A
21

To anyone else who doesn't want or can't suppress the warning.

This is happening because ngrams is raising StopIteration exception to end a generator, and this is deprecated from Python 3.5.

You could get rid of the warning by changing the code where the generator stops, so instead of raising StopIteration you just use Python's keyword return.

More on: PEP 479

Airlike answered 5/10, 2017 at 22:18 Comment(2)
I have a generator: while True: yield itertools.chain(...). How would you convert that?Shandra
@Shandra You can use this: yield from itertools.chain(...).Illlooking
B
4

You can use a wrapper like this one:

def get_data(gen):
    try:
        for elem in gen:
            yield elem
    except (RuntimeError, StopIteration):
        return

and then (according to your example):

data = get_data(ngrams(tokens, 3))

should do the trick

Boucicault answered 19/11, 2018 at 11:42 Comment(1)
or just yield from genSpeleology
U
0

If you just want to quiet all warnings, you can do:

import warnings

warnings.filterwarnings('ignore')

We should listen to these warnings...

Unfeigned answered 23/8, 2018 at 0:41 Comment(2)
Nobody do this, you stand to miss all sorts of important and relevant warnings. They wouldn't exist unless the core developers made some sort of mistake. Just fix your code.Mucoprotein
Sometimes warnings are triggered by third party libraries and one can't simply change that source code. I agree one should be cautious when filtering warnings--as always in programming, with great power comes great responsibility. You should only filter warnings if you know what you're doing...Unfeigned

© 2022 - 2024 — McMap. All rights reserved.