[Python-ideas] Potential PEP: with/except
Chris Angelico
rosuav at gmail.com
Tue Jan 22 17:49:57 EST 2019
On Wed, Jan 23, 2019 at 9:23 AM Paul Ferrell <pflarr at gmail.com> wrote:
>
> That is definitely an ambiguity worth considering (whether __enter__ is within the implied 'try').
>
It's not even __enter__.
>>> import dis
>>> def f(path):
... with open(path) as f:
... print("Got f:", f)
...
>>> dis.dis(f)
2 0 LOAD_GLOBAL 0 (open)
2 LOAD_FAST 0 (path)
4 CALL_FUNCTION 1
6 SETUP_WITH 16 (to 24)
8 STORE_FAST 1 (f)
3 10 LOAD_GLOBAL 1 (print)
12 LOAD_CONST 1 ('Got f:')
14 LOAD_FAST 1 (f)
16 CALL_FUNCTION 2
18 POP_TOP
20 POP_BLOCK
22 BEGIN_FINALLY
>> 24 WITH_CLEANUP_START
26 WITH_CLEANUP_FINISH
28 END_FINALLY
30 LOAD_CONST 0 (None)
32 RETURN_VALUE
>>>
At the time when "open(path)" is called, the 'with' block hasn't begun
operating yet. The SETUP_WITH operation will call __enter__, but prior
to that, we have to have an object to use as the context manager. Any
exception thrown by opening the file will happen before __enter__ gets
called. AIUI the __enter__ method of file objects doesn't actually do
anything much (just validates that it's still open).
ChrisA
More information about the Python-ideas
mailing list