Interactive ConveniencesΒΆ

When developing projects using codetransformer, it’s often helpful to be able to quickly and easily visualize the AST and/or disassembly generated by CPython for a given source text.

The codetransformer.utils.pretty module provides utilities for viewing AST trees and the disassembly of nested code objects:

a(text[, mode, indent, file]) Interactive convenience for displaying the AST of a code string.
d(obj[, mode, file]) Interactive convenience for displaying the disassembly of a function, module, or code string.
display(text[, mode, file]) Show text, rendered as AST and as Bytecode.
extract_code(obj, compile_mode) Generic function for converting objects into instances of CodeType.

For users of IPython, codetransformer provides an IPython extension that adds %%ast and %%dis magics.

 In [1]: %load_ext codetransformer
 In [2]: %%dis
    ...: def foo(a, b):
    ...:     return a + b
    ...:
 <module>
 --------
   1           0 LOAD_CONST               0 (<code object foo at 0x7f4c428a9b70, file "<show>", line 1>)
               3 LOAD_CONST               1 ('foo')
               6 MAKE_FUNCTION            0
               9 STORE_NAME               0 (foo)
              12 LOAD_CONST               2 (None)
              15 RETURN_VAL

 <module>.foo
 ------------
   2           0 LOAD_FAST                0 (a)
               3 LOAD_FAST                1 (b)
               6 BINARY_ADD
               7 RETURN_VAL


In [3]: %%ast
    ...: def foo(a, b):
    ...:     return a + b
    ...:
 Module(
   body=[
     FunctionDef(
       name='foo',
       args=arguments(
         args=[
           arg(
             arg='a',
             annotation=None,
           ),
           arg(
             arg='b',
             annotation=None,
           ),
         ],
         vararg=None,
         kwonlyargs=[],
         kw_defaults=[],
         kwarg=None,
         defaults=[],
       ),
       body=[
         Return(
           value=BinOp(
             left=Name(id='a', ctx=Load()),
             op=Add(),
             right=Name(id='b', ctx=Load()),
           ),
         ),
       ],
       decorator_list=[],
       returns=None,
     ),
   ],
 )