[Python-ideas] Augment dis.dis to autocompile strings
Nick Coghlan
ncoghlan at gmail.com
Sat Jul 18 00:52:21 CEST 2009
Steven D'Aprano wrote:
> On Fri, 17 Jul 2009 04:35:40 am Terry Reedy wrote:
>
>> Proposal: if the input is a string, do the above (do what I mean)
>> instead of raising
>> TypeError: don't know how to disassemble str objects
>>
>> Any negatives before I submit a feature request?
>
> +1 on the idea, but how do you determine which of the following are
> required?
>
> compile('x+1', '', 'eval')
> compile('x = x+1', '', 'single')
> compile('while x < 42: x += 1', '', 'exec')
>
>
> Or do you just assume 'exec'?
We could define it as trying the three in order (first 'eval', then
'single', then 'exec') moving on to the next option if it raises syntax
error:
from dis import dis
def dis_str(source):
modes = ('eval', 'single', 'exec')
for mode in modes:
try:
c = compile(source, '', mode)
break
except SyntaxError:
if mode is modes[-1]:
raise
return dis(c)
>>> dis_str("x+1")
1 0 LOAD_NAME 0 (x)
3 LOAD_CONST 0 (1)
6 BINARY_ADD
7 RETURN_VALUE
>>> dis_str("x = x+1")
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_str("while x < 42: x += 1")
1 0 SETUP_LOOP 26 (to 29)
>> 3 LOAD_NAME 0 (x)
6 LOAD_CONST 0 (42)
9 COMPARE_OP 0 (<)
12 POP_JUMP_IF_FALSE 28
15 LOAD_NAME 0 (x)
18 LOAD_CONST 1 (1)
21 INPLACE_ADD
22 STORE_NAME 0 (x)
25 JUMP_ABSOLUTE 3
>> 28 POP_BLOCK
>> 29 LOAD_CONST 2 (None)
32 RETURN_VALUE
>>> dis_str("bad syntax still goes boom")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 5, in dis_str
File "", line 1
bad syntax still goes boom
^
SyntaxError: invalid syntax
Cheers,
Nick.
--
Nick Coghlan | ncoghlan at gmail.com | Brisbane, Australia
---------------------------------------------------------------
More information about the Python-ideas
mailing list