Ask Your Question

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

asked 2016-06-28 18:14:23 +0200

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 16:24:06 +0200 )edit

1 Answer

Sort by ยป oldest newest most voted

answered 2016-06-28 23:54:50 +0200

slelievre gravatar image

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 20:46:34 +0200 )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 18:14:23 +0200

Seen: 3,204 times

Last updated: Jun 28 '16