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
{
"metadata": {
"name": "With Magic Demo"
},
"nbformat": 3,
"nbformat_minor": 0,
"worksheets": [
{
"cells": [
{
"cell_type": "code",
"collapsed": false,
"input": [
"%load_ext withmagic"
],
"language": "python",
"metadata": {},
"outputs": [],
"prompt_number": 1
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"%with open('withmagic.py') as f:"
],
"language": "python",
"metadata": {},
"outputs": [
{
"output_type": "stream",
"stream": "stdout",
"text": [
"Context manager f started\n"
]
}
],
"prompt_number": 2
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"print(f.readline())"
],
"language": "python",
"metadata": {},
"outputs": [
{
"output_type": "stream",
"stream": "stdout",
"text": [
"# -*- coding: utf-8 -*-\n",
"\n"
]
}
],
"prompt_number": 3
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"len(f.readlines())"
],
"language": "python",
"metadata": {},
"outputs": [
{
"output_type": "pyout",
"prompt_number": 4,
"text": [
"54"
]
}
],
"prompt_number": 4
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"%endwith"
],
"language": "python",
"metadata": {},
"outputs": [
{
"output_type": "stream",
"stream": "stdout",
"text": [
"Context manager f ended\n"
]
}
],
"prompt_number": 5
}
],
"metadata": {}
}
]
}
# -*- 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