# -*- coding: utf-8 -*-

import keyword as kw
import sympy
from repr import ReprPrinter
from str import StrPrinter

# A list of classes that should be printed using StrPrinter
STRPRINT = ("Add", "Infinity", "Integer", "Mul", "NegativeInfinity",
            "Pow", "Zero")

class PythonPrinter(ReprPrinter, StrPrinter):
    """A printer which converts an expression into its Python interpretation."""

    def __init__(self, settings=None):
        ReprPrinter.__init__(self)
        StrPrinter.__init__(self, settings)
        self.symbols = []
        self.functions = []

        # Create print methods for classes that should use StrPrinter instead
        # of ReprPrinter.
        for name in STRPRINT:
            f_name = "_print_%s"%name
            f = getattr(StrPrinter, f_name)
            setattr(PythonPrinter, f_name, f)

    def _print_Function(self, expr):
        func = expr.func.__name__
        if not hasattr(sympy, func) and not func in self.functions:
            self.functions.append(func)
        return StrPrinter._print_Function(self, expr)

    # procedure (!) for defining symbols which have be defined in print_python()
    def _print_Symbol(self, expr):
        symbol = self._str(expr)
        if symbol not in self.symbols:
            self.symbols.append(symbol)
        return StrPrinter._print_Symbol(self, expr)

    def _print_module(self, expr):
        raise ValueError('Modules in the expression are unacceptable')


def python(expr, **settings):
    """Return Python interpretation of passed expression
    (can be passed to the exec() function without any modifications)"""

    printer = PythonPrinter(settings)
    exprp = printer.doprint(expr)

    result = ''
    # Returning found symbols and functions
    renamings = {}
    for symbolname in printer.symbols:
        newsymbolname = symbolname
        if kw.iskeyword(newsymbolname):
            while True:
                newsymbolname += "_"
                if (newsymbolname not in printer.symbols and
                    newsymbolname not in printer.functions):
                    renamings[sympy.Symbol(symbolname)] = sympy.Symbol(newsymbolname)
                    break
        result += newsymbolname + ' = Symbol(\'' + symbolname + '\')\n'

    for functionname in printer.functions:
        newfunctionname = functionname
        # TODO
        # Escape function names that are reserved python keywords
        # Fix does not work because we can not xreplace functions!
        # if kw.iskeyword(newfunctionname):
        #     while True:
        #         newfunctionname += "_"
        #         if (newfunctionname not in printer.symbols and
        #             newfunctionname not in printer.functions):
        #             renamings[sympy.Function(functionname)] = sympy.Function(newfunctionname)
        #             break
        result += newfunctionname + ' = Function(\'' + functionname + '\')\n'

    if not len(renamings) == 0:
        exprp = expr.xreplace(renamings)
    result += 'e = ' + printer._str(exprp)
    return result

def print_python(expr, **settings):
    """Print output of python() function"""
    print python(expr, **settings)

@@ -1835,24 +1835,88 @@
  symbolname%0A
+        # Escape symbol names that are reserved python keywords%0A
         if k
@@ -1939,24 +1939,24 @@
 ymbolname):%0A
-
             
@@ -2397,23 +2397,8 @@
 ame%0A
-        # TODO%0A
     
@@ -2470,77 +2470,8 @@
     
- # Fix does not work because we can not xreplace functions!%0A        #
  if 
@@ -2504,26 +2504,24 @@
 me):%0A       
- #
      while T
@@ -2524,34 +2524,32 @@
 le True:%0A       
- #
          newfunc
@@ -2563,34 +2563,32 @@
 e += %22_%22%0A       
- #
          if (new
@@ -2627,33 +2627,32 @@
 ols and%0A        
-#
              new
@@ -2639,33 +2639,32 @@
                 
- 
 newfunctionname 
@@ -2689,34 +2689,32 @@
 ctions):%0A       
- #
              ren
@@ -2791,18 +2791,16 @@
 %0A       
- #
         
@@ -2946,16 +2946,12 @@
 xpr.
-xreplace
+subs
 (ren

Make function name escaping work