First time here? Check out the FAQ!

Ask Your Question
1

How to import rings in python module

asked 4 years ago

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 https://doc.sagemath.org/html/en/tuto... by importing packages with command line such as

import_statements('is_integer')

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?

Preview: (hide)

1 Answer

Sort by » oldest newest most voted
2

answered 4 years ago

tmonteil gravatar image

updated 4 years ago

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')
'Integer(1)/Integer(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.

Preview: (hide)
link

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

Stats

Asked: 4 years ago

Seen: 438 times

Last updated: Jan 21 '21