Quantcast
Viewing all articles
Browse latest Browse all 14069

How do I define __contains__ for a Python Generator() returned by a function?

The following example:

def myGenerator():    i = -1    while i < 1000000:        print(f"iterating {i}")        i+=1        yield iprint(9999 in myGenerator())

Prints in the console

...iterating 9994iterating 9995iterating 9996iterating 9997iterating 9998True

The generator iterates over all items until it finds '9999'(which in the end of the day then makes it rather pointless to use a generator to begin with as opposed to having my function return a tuple or a list).

Would it be possible to define __contains__ on the Generator() object returned by my myGenerator function to avoid iterating over all items ? If so, how?


Viewing all articles
Browse latest Browse all 14069

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>