Skip to content

Instantly share code, notes, and snippets.

@timothyb89
Created February 28, 2014 19:56
Show Gist options
  • Save timothyb89/9278578 to your computer and use it in GitHub Desktop.
Save timothyb89/9278578 to your computer and use it in GitHub Desktop.
SymPy in IPython with naked constants
#
# ~/.config/ipython/extensions/baresympy.py
#
#
# This automatically "Sympifies" naked constants (i.e. performs S(123) automatically)
# It's smart enough to keep compatibility with SymPy functionality (e.g. plot ranges)
# but will probably break your console for anything not SymPy related.
#
# Use "%load_ext baresympy" to load, or add it to your IPython profile.
#
import sys
import traceback
from copy import deepcopy
from ast import copy_location, iter_fields
from ast import NodeTransformer, Call, Name, Load
from ast import Num, BinOp, List
from IPython.core.inputtransformer import StatelessInputTransformer
def wrap(node):
return Call(
func = Name(id = 'sympify', ctx = Load()),
args = [ node ],
keywords = [])
def num_search_recurse(node):
ret = []
if not hasattr(node, '_fields'):
return ret
for name, value in iter_fields(node):
if isinstance(value, Num):
ret.append((node, name, value))
elif isinstance(value, List):
# skip, don't break lists
pass
else:
ret.extend(num_search_recurse(value))
return ret
def wrap_descend(node):
for parent, field, value in num_search_recurse(node):
setattr(parent, field, wrap(value))
class SympyWrapper(NodeTransformer):
def visit_Expr(self, node):
ret = deepcopy(node)
try:
wrap_descend(ret)
except:
traceback.print_exc()
return ret
def visit_Assign(self, node):
ret = deepcopy(node)
try:
wrap_descend(ret)
except:
traceback.print_exc()
return ret
def load_ipython_extension(ip):
ip.ast_transformers.append(SympyWrapper())
#
# ~/.config/ipython/profile_default/startup/spc.py
#
from __future__ import division
from sympy import *
x, y, z = symbols('x y z')
k, m, n = symbols('k m n', integer = True)
f, g, h = symbols('f g h', cls = Function)
init_printing(use_latex = True)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment