IPython extension allowing visualizing AST of cell using magic
Project description
This allows you to visualize the AST of a cell in IPython upon running it.
Installation
pip3 install ast-magic
To manually load, run the following in your IPython prompt:
%load_ext ast_magic
To automatically load, add the following to your IPython configuration file:
c = get_config()
c.InteractiveShellApp.extensions.append('ast_magic')
Usage
Verifying Python follows PEMDAS:
In [1]: %ast (1 + 1) ** 2 * 5 - 4
Module(
body=[
Expr(
value=BinOp(
left=BinOp(
left=BinOp(
left=BinOp(
left=Constant(value=1),
op=Add(),
right=Constant(value=1)),
op=Pow(),
right=Constant(value=2)),
op=Mult(),
right=Constant(value=5)),
op=Sub(),
right=Constant(value=4)))],
type_ignores=[])
You can use it in a cell too:
In [1]: %%ast
...:
...: def fibonacci(n: int) -> int:
...: if n <= 1: return 1
...: return fibonacci(n - 2) + fibonacci(n - 1)
...:
Module(
body=[
FunctionDef(
name='fibonacci',
args=arguments(
posonlyargs=[],
args=[
arg(
arg='n',
annotation=Name(id='int', ctx=Load()))],
kwonlyargs=[],
kw_defaults=[],
defaults=[]),
body=[
If(
test=Compare(
left=Name(id='n', ctx=Load()),
ops=[
LtE()],
comparators=[
Constant(value=1)]),
body=[
Return(
value=Constant(value=1))],
orelse=[]),
Return(
value=BinOp(
left=Call(
func=Name(id='fibonacci', ctx=Load()),
args=[
BinOp(
left=Name(id='n', ctx=Load()),
op=Sub(),
right=Constant(value=2))],
keywords=[]),
op=Add(),
right=Call(
func=Name(id='fibonacci', ctx=Load()),
args=[
BinOp(
left=Name(id='n', ctx=Load()),
op=Sub(),
right=Constant(value=1))],
keywords=[])))],
decorator_list=[],
returns=Name(id='int', ctx=Load()))],
type_ignores=[])
Project details
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
ast-magic-1.0.1.tar.gz
(2.4 kB
view hashes)
Built Distribution
Close
Hashes for ast_magic-1.0.1-py3-none-any.whl
Algorithm | Hash digest | |
---|---|---|
SHA256 | 810c40883c9cff971ea865a35ca54d0a9cd71282de256137bd51d4a286a5cd62 |
|
MD5 | e3474e4bf4e140014ea15fb62de30e16 |
|
BLAKE2b-256 | f62c2b35c097acb76d9e6077b70a1d0996434178f8d1e6c2b60649e5a11a502b |