Skip to content

Instantly share code, notes, and snippets.

@tdhopper
Created January 4, 2020 21:18
Show Gist options
  • Save tdhopper/1b41e04b121c988361dfc2582057f5b4 to your computer and use it in GitHub Desktop.
Save tdhopper/1b41e04b121c988361dfc2582057f5b4 to your computer and use it in GitHub Desktop.
from io import BytesIO
def render_altair(chart):
b = BytesIO()
chart.save(b, scale_factor=2.0, format='png', webdriver='firefox')
b.seek(0)
return b.read()
import ast
def exec_then_eval(code, shell):
block = ast.parse(code, mode='exec')
# assumes last node is an expression
last = ast.Expression(block.body.pop().value)
_globals, _locals = {}, {}
shell.ex(compile(block, '<string>', mode='exec'))
return shell.ev(compile(last, '<string>', mode='eval'))
@magics_class
class AltairMagic(Magics):
@cell_magic
def altair(self, line, cell):
return Image(render_altair(exec_then_eval(cell, self.shell)))
ip = get_ipython()
ip.register_magics(AltairMagic)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment