Ask Your Question

Can I create a sage file, and import it as a Python module?

asked 2016-06-28 11:14:23 -0500

silvia_n_nets gravatar image

I am trying to create a file that produces some data using sage specific modules (eg graphs. ). Is there a way that I can save this file and then import it in a Python shell and / or in a Sage shell?

The problems I have encountered so far are:

  • if I try to save the file as and import it as a module in a Python or Sage shell, Python/ Sage won't recognize the sage specific functions (which makes sense)
  • if I try to save the file as filename.sage and import it as a module in a Sage shell, I get the error "No module named filename"

I am working from an Ubuntu terminal.

Thank you!

edit retag flag offensive close merge delete


I just know that the standard way to import a file is :

sage: load /path/to/


sage: attach /path/to/

But I guess I need to read more about Python

MargaretMitchel gravatar imageMargaretMitchel ( 2016-06-30 09:24:06 -0500 )edit

1 answer

Sort by ยป oldest newest most voted

answered 2016-06-28 16:54:50 -0500

The solution is to use a file.

For the sage specific syntax, find the corresponding Python code using preparse.

Find the sage specific functions to import using import_statements.

For example, suppose that your sage file has

R.<x> = PolynomialRing(QQ)

which is not correct Python syntax. Check how to turn that into correct Python.

sage: preparse('R.<x> = PolynomialRing(QQ)')
"R = PolynomialRing(QQ, names=('x',)); (x,) = R._first_ngens(1)"

so in you would write

R = PolynomialRing(QQ, names=('x',))
(x,) = R._first_ngens(1)

instead of

R.<x> = PolynomialRing(QQ)

You would also need the import statements, which you find with

sage: import_statements('PolynomialRing')
from sage.rings.polynomial.polynomial_ring_constructor import PolynomialRing
sage: import_statements('QQ')
from sage.rings.rational_field import QQ

So your python file would really have

from sage.rings.polynomial.polynomial_ring_constructor import PolynomialRing
from sage.rings.rational_field import QQ

R = PolynomialRing(QQ, names=('x',))
(x,) = R._first_ngens(1)
edit flag offensive delete link more


For the syntax, you can run sage -preparse file.sage from the command line and it will do all of the syntax conversions for you. It will also add the line from sage.all import * at the top, though you have to then run this with Sage's version of Python (or tell Python where to find sage.all).

jaebond gravatar imagejaebond ( 2016-07-26 13:46:34 -0500 )edit

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account.

Add Answer

Question Tools


Asked: 2016-06-28 11:14:23 -0500

Seen: 479 times

Last updated: Jun 28 '16