[New-bugs-announce] [issue6507] Enhance dis.dis to autocompile codestrings

Terry J. Reedy report at bugs.python.org
Fri Jul 17 21:06:15 CEST 2009


New submission from Terry J. Reedy <tjreedy at udel.edu>:

dis.dis(ob) currently accepts "a module, a class, a method, a function,
or a code object." But for most uses I have seen on python-list, people
start with a code snippet. They must then wrap that in a function or
remember (or lookup) a call such as compile(code, '', 'exec') to make a
code object. I propose that dis do the latter automatically. Dis already
has to branch on the input class, so I assume adding another branch
should not be difficult.

On the Python ideas list, Steven D'Aprano raised the issue of 'exec'
versus 'single' versus 'eval'. As far as dis is concerned, there seems
to be no difference between 'exec' and 'single'.

>>> dis(compile('x = x+1', '', 'single'))
  1           0 LOAD_NAME                0 (x) 
              3 LOAD_CONST               0 (1) 
              6 BINARY_ADD           
              7 STORE_NAME               0 (x) 
             10 LOAD_CONST               1 (None) 
             13 RETURN_VALUE         

>>> dis(compile('x = x+1', '', 'exec'))
  1           0 LOAD_NAME                0 (x) 
              3 LOAD_CONST               0 (1) 
              6 BINARY_ADD           
              7 STORE_NAME               0 (x) 
             10 LOAD_CONST               1 (None) 
             13 RETURN_VALUE         

Using 'exec' instead of 'eval' adds two spurious, but easily ignored, lines.

>>> dis(compile('x+1','', 'eval'))
  1           0 LOAD_NAME                0 (x) 
              3 LOAD_CONST               0 (1) 
              6 BINARY_ADD           
              7 RETURN_VALUE    
     
>>> dis(compile('x+1', '', 'exec'))
  1           0 LOAD_NAME                0 (x) 
              3 LOAD_CONST               0 (1) 
              6 BINARY_ADD           
              7 POP_TOP              
              8 LOAD_CONST               1 (None) 
             11 RETURN_VALUE         

Between the current doc sentences "For a single code sequence, it prints
one line per bytecode instruction." and "If no object is provided, it
disassembles the last traceback." I propose adding the following two
sentences.

"Strings are first compiled as statements to code objects with
compile(string,'','exec'). For expressions, this adds a spurious POP_TOP
and LOAD_CONST at the end."

'compile' should be cross-referenced to its listing under built-in
functions.

----------
components: Library (Lib)
messages: 90637
nosy: tjreedy
severity: normal
status: open
title: Enhance dis.dis to autocompile codestrings
type: feature request
versions: Python 3.2

_______________________________________
Python tracker <report at bugs.python.org>
<http://bugs.python.org/issue6507>
_______________________________________


More information about the New-bugs-announce mailing list