[Python-Dev] Exception message for invalid with statement usage

Nick Coghlan ncoghlan at gmail.com
Wed Sep 6 15:11:31 CEST 2006


Georg Brandl wrote:
> Current trunk:
> 
>>>> with 1:
> ...  print "1"
> ...
> Traceback (most recent call last):
>   File "<stdin>", line 1, in <module>
> AttributeError: 'int' object has no attribute '__exit__'
> 
> Isn't that a bit crude? For "for i in 1" there's a better
> error message, so why shouldn't the above give a
> TypeError: 'int' object is not a context manager

The for loop has a nice error message because it starts with its own opcode, 
but the with statement translates pretty much to the code in PEP 343. There's 
a special opcode at the end to help with unwinding the stack, but at the start 
it's just normal attribute retrieval opcodes for __enter__ and __exit__.

 >>> def f():
...   with 1:
...     pass
...
 >>> dis.dis(f)
   2           0 LOAD_CONST               1 (1)
               3 DUP_TOP
               4 LOAD_ATTR                0 (__exit__)
               7 STORE_FAST               0 (_[1])
              10 LOAD_ATTR                1 (__enter__)
              13 CALL_FUNCTION            0
              16 POP_TOP
              17 SETUP_FINALLY            4 (to 24)

   3          20 POP_BLOCK
              21 LOAD_CONST               0 (None)
         >>   24 LOAD_FAST                0 (_[1])
              27 DELETE_FAST              0 (_[1])
              30 WITH_CLEANUP
              31 END_FINALLY
              32 LOAD_CONST               0 (None)
              35 RETURN_VALUE

Cheers,
Nick.

-- 
Nick Coghlan   |   ncoghlan at gmail.com   |   Brisbane, Australia
---------------------------------------------------------------
             http://www.boredomandlaziness.org


More information about the Python-Dev mailing list