Ask Your Question

How to import rings in python module

asked 2021-01-21 07:10:55 +0100

I'm trying to build a sage 9 code into a format of python module with .py file, and run the module in the sage command line. Most of the issue could be fixed through this webpage by importing packages with command line such as


i.e. set up the sage environment manually. However, a built in mechanism in sage was the usage of rings. i.e. 1/3 in sage automatically returned 1/3 in rational ring, but when put the code in python module and run it in sage command line.

sage: module_name.value1

was in class 'float' or 'int'

How to set up the environment so that the module could run operation in sage rings automatically?

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted

answered 2021-01-21 10:11:41 +0100

tmonteil gravatar image

updated 2021-01-21 10:15:05 +0100

At startup, Sage does not only import things, it also adds a preparser, so that what you typed in Sage is modified on the fly to some valid Python:

sage: type(1/3)
<class 'sage.rings.rational.Rational'>

If we turn the preparser off, we get:

sage: preparser(False)
sage: type(1/3)
<class 'float'>

To see how the preparser modified 1/3, you can do:

sage: preparse('1/3')

and check:

sage: type(Integer(1)/Integer(3))
<class 'sage.rings.rational.Rational'>

So, to transform some Sage code into a Python module, you have to both add import statements and preparse it.

You could notice that the Sage source code is pure Python, i.e. does not rely on preparser either, maybe looking at it could help to get the idea.

edit flag offensive delete link more

Your Answer

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

Add Answer

Question Tools

1 follower


Asked: 2021-01-21 07:10:55 +0100

Seen: 38 times

Last updated: Jan 21