1212
1313_have_code = (types .MethodType , types .FunctionType , types .CodeType , type )
1414
15+ def _try_compile (source , name ):
16+ """Attempts to compile the given source, first as an expression and
17+ then as a statement if the first approach fails.
18+
19+ Utility function to accept strings in functions that otherwise
20+ expect code objects
21+ """
22+ # ncoghlan: currently only used by dis(), but plan to add an
23+ # equivalent for show_code() as well (but one that returns a
24+ # string rather than printing directly to the console)
25+ try :
26+ c = compile (source , name , 'eval' )
27+ except SyntaxError :
28+ c = compile (source , name , 'exec' )
29+ return c
30+
1531def dis (x = None ):
1632 """Disassemble classes, methods, functions, or code.
1733
@@ -38,7 +54,9 @@ def dis(x=None):
3854 elif hasattr (x , 'co_code' ):
3955 disassemble (x )
4056 elif isinstance (x , (bytes , bytearray )):
41- disassemble_string (x )
57+ _disassemble_bytes (x )
58+ elif isinstance (x , str ):
59+ _disassemble_str (x )
4260 else :
4361 raise TypeError ("don't know how to disassemble %s objects" %
4462 type (x ).__name__ )
@@ -157,7 +175,7 @@ def disassemble(co, lasti=-1):
157175 print ('(' + free [oparg ] + ')' , end = ' ' )
158176 print ()
159177
160- def disassemble_string (code , lasti = - 1 , varnames = None , names = None ,
178+ def _disassemble_bytes (code , lasti = - 1 , varnames = None , names = None ,
161179 constants = None ):
162180 labels = findlabels (code )
163181 n = len (code )
@@ -196,6 +214,10 @@ def disassemble_string(code, lasti=-1, varnames=None, names=None,
196214 print ('(' + cmp_op [oparg ] + ')' , end = ' ' )
197215 print ()
198216
217+ def _disassemble_str (source ):
218+ """Compile the source string, then disassemble the code object."""
219+ disassemble (_try_compile (source , '<dis>' ))
220+
199221disco = disassemble # XXX For backwards compatibility
200222
201223def findlabels (code ):
0 commit comments