New submission from reidfaiv: 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. ---------- components: Interpreter Core files: gen_err.py messages: 261497 nosy: reidfaiv priority: normal severity: normal status: open title: NameError for built in function open when re-raising stored exception from yielded function type: behavior versions: Python 3.4, Python 3.5 Added file: http://bugs.python.org/file42114/gen_err.py _______________________________________ Python tracker <rep...@bugs.python.org> <http://bugs.python.org/issue26528> _______________________________________ _______________________________________________ Python-bugs-list mailing list Unsubscribe: https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com