Message261497
Builtin open() gets NameError) in context manager __exit__ in case:
* context manager yielding records
* we return another generator when consuming these and
* second generator raises, catches, stores and re-raises an excption
Reduced down code looks like this:
---------------------------------------
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# context manager "query" (open in init, yield rows and close on exit)
class _query():
def __init__(self, **kwargs):
pass
def __enter__(self):
return [1, 2, 3]
def __exit__(self, type_, value, tb):
print('__exit__') # print() is also built-in, but works
f = open('test.log', 'wt') # <-- NameError: name 'open' is not defined
f.close()
# this works fine
def a():
try:
raise Exception('volatile exception')
except Exception as e:
raise e
# this does not work
def b():
try:
raise Exception('stored exception')
except Exception as e:
ee = e # <-- storing exception and then
raise ee # <-- re-raising stored exception triggers the issue
def event_gen(**kwargs):
with _query() as cursor:
for _ in cursor:
yield b # <--- does not work
# yield a # <--- works fine
def run(**kwargs):
g = event_gen(**kwargs)
r = next(g)
r()
# This also works
# for r in event_gen(**kwargs):
# r()
if __name__ == '__main__':
run()
---------------------------------------
>python.exe gen_err.py
Traceback (most recent call last):
File "gen_err.py", line 52, in <module>
run()
File "gen_err.py", line 46, in run
r()
File "gen_err.py", line 33, in b
raise ee # <-- re-raising stored exception triggers the issue
File "gen_err.py", line 30, in b
raise Exception('stored exception')
Exception: stored exception
__exit__
Exception ignored in: <generator object event_gen at 0x000001A31F7C4048>
Traceback (most recent call last):
File "gen_err.py", line 39, in event_gen
File "gen_err.py", line 15, in __exit__
NameError: name 'open' is not defined
This happens with Python 3.4+
Works with earlier versions as expected.
If exception re-raised immediately, works fine.
If outermost generator is consumed in for loop, works fine. |
|
Date |
User |
Action |
Args |
2016-03-10 12:09:57 | reidfaiv | set | recipients:
+ reidfaiv |
2016-03-10 12:09:57 | reidfaiv | set | messageid: <1457611797.69.0.202848672993.issue26528@psf.upfronthosting.co.za> |
2016-03-10 12:09:57 | reidfaiv | link | issue26528 messages |
2016-03-10 12:09:57 | reidfaiv | create | |
|