inyeol....@gmail.com wrote, on January 29, 2017 9:24 PM > > Does generator.close() prevent raising StopIteration? > > I'm trying to get the return value from coroutine after > terminating it. Here is simple test code: > > $ python3 > Python 3.6.0 (default, Dec 23 2016, 12:50:55) > [GCC 4.2.1 Compatible Apple LLVM 8.0.0 (clang-800.0.38)] on > darwin Type "help", "copyright", "credits" or "license" for > more information. > >>> def cor(): > ... try: > ... item = yield > ... except GeneratorExit: > ... return 1 > ... > >>> c = cor() > >>> next(c) > >>> c.close() > >>> > > I was expecting StopIteration from c.close() call, but Python > 3.6 doesn't raise any. Is this behavior expected? I couldn't > find any reference regarding GeneratorExit and StopIteration > interaction.
Use except StopIteration: (Not sure what generator.close() should do, or if GeneratorExit is any kind of equivalent, but StopIteration works. I'm less familiar with Python 2.) Python 3.4.3 |Anaconda 2.3.0 (32-bit)| (default, Mar 6 2015, 12:08:17) [MSC v.1600 32 bit (Intel)] on win32 Type "copyright", "credits" or "license()" for more information. >>> help(generator.close) Traceback (most recent call last): File "<pyshell#0>", line 1, in <module> help(generator.close) NameError: name 'generator' is not defined So at the very least, generator needs to be defined, if it's possible to define or import it in Python 3. Probably not. In Python 2, GeneratorExit is raised when the generator's close() method is called. But in my quick search, I couldn't find GeneratorExit in Python 3, or any note that it had been dropped, but it's a good guess that it was dropped. It's redundant with StopIteration. I always use StopIteration. It works in all Python versions. -- https://mail.python.org/mailman/listinfo/python-list