pyutils.py 838 B

123456789101112131415161718192021222324
  1. from sympy.printing.pycode import PythonCodePrinter
  2. """ This module collects utilities for rendering Python code. """
  3. def render_as_module(content, standard='python3'):
  4. """Renders Python code as a module (with the required imports).
  5. Parameters
  6. ==========
  7. standard :
  8. See the parameter ``standard`` in
  9. :meth:`sympy.printing.pycode.pycode`
  10. """
  11. printer = PythonCodePrinter({'standard':standard})
  12. pystr = printer.doprint(content)
  13. if printer._settings['fully_qualified_modules']:
  14. module_imports_str = '\n'.join('import %s' % k for k in printer.module_imports)
  15. else:
  16. module_imports_str = '\n'.join(['from %s import %s' % (k, ', '.join(v)) for
  17. k, v in printer.module_imports.items()])
  18. return module_imports_str + '\n\n' + pystr