Skip to content

Instantly share code, notes, and snippets.

@bfroehle
Last active December 16, 2015 07:49
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save bfroehle/5401361 to your computer and use it in GitHub Desktop.
Save bfroehle/5401361 to your computer and use it in GitHub Desktop.
%with / %endwith IPython extension
Display the source blob
Display the rendered blob
Raw
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
# -*- coding: utf-8 -*-
"""
%with and %endwith magics.
"""
#-----------------------------------------------------------------------------
# Imports
#-----------------------------------------------------------------------------
import re
from IPython.core.error import UsageError
from IPython.core.magic import Magics, magics_class, line_magic
#-----------------------------------------------------------------------------
# Functions and classes
#-----------------------------------------------------------------------------
@magics_class
class WithMagics(Magics):
"""Provides the %with and %endwith magics."""
def __init__(self, shell):
super(WithMagics, self).__init__(shell)
self._re_with = re.compile(r'^(?P<code>.*)\s+as\s+(?P<name>[_A-Za-z][_A-Za-z0-9]*):$')
self._contexts = []
@line_magic('with')
def with_(self, line=''):
m = self._re_with.match(line)
if not m:
raise UsageError("Error parsing statement.")
code = m.group('code')
name = m.group('name')
shell = self.shell
context = eval(code, shell.user_global_ns, shell.user_ns)
obj = context.__enter__()
print("Context manager %s started" % name)
# Return value to the user
shell.user_ns[name] = obj
self._contexts.append((name, context))
@line_magic
def endwith(self, line=''):
name, context = self._contexts.pop()
print("Context manager %s ended" % name)
context.__exit__(None, None, None)
def load_ipython_extension(ip):
"""Load the extension in IPython."""
ip.register_magics(WithMagics)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment