Using SageMath as a python library

Question:

Is it possible to import the SageMath functions inside a python session?

What I wish to do, from a user perspective is something like this:

>>> import sage
>>> sage.kronecker_symbol(3,5)  # ...or any other sage root functions

instead of accessing kronecker_symbol(3,5) from a sagemath session.
If possible, it would be very handy, as would allow embedding all the functionalities of SageMath within the python world.

Asked By: SeF

||

Answers:

Importing SageMath functions in a Python session

There are several ways to achieve that.

SageMath from the operating system’s package manager

Some operating systems have Sage packaged natively,
for example Arch Linux, Debian, Fedora, Gentoo, NixOS,
and their derivatives (Linux Mint, Manjaro, Ubuntu…).

See the dedicated “Distribution” page on the Sage wiki:

If using one of those, use the package manager
to install sage or sagemath and then the
Sage library will be installed on the system’s
Python, and in that Python it will become possible
to do things like

>>> from sage.arith.misc import kronecker
>>> kronecker(3, 5)
-1

Another option is to use a cross-platform package manager
such as Conda, Guix and Nix. These should work on most
Linux distributions and macOS. Yet another option would be
to run a Docker container.

I will detail the Conda case below.

SageMath with Conda

Install Sage with Conda and you will get that.

Instructions are here:

and start by installing a Conda distribution, either
Miniconda, Minimamba or Anaconda, and then creating a
sage conda environment.

Once a sage conda environment is installed, activate it:

conda activate sage

With that sage conda environment active, run

python

and importing the sage module or importing functions
such as kronecker from that module should work.

Answered By: Samuel Lelièvre

This is a complementary answer for those who fail to use some SageMath function that is not compatible with Python syntax.

For example;

from sage.all import *

F = GF(2)
R.<x> = k[]

This will give an error on R.<x> = k[] since it is not a valid Python syntax. So how to solve this issue?

SageMath parses the SageMath syntax then use Python. One needs to use preparse to see the actual command.

sage: preparse('R.<x> = k[]')
"R = k['x']; (x,) = R._first_ngens(1)"

So replace the line, done!

from sage.all import *

F = GF(2)
R = k['x']; (x,) = R._first_ngens(1)

Unfortunately one must use SageMath to identify these.

Answered By: kelalaka

1/ pip install sage
2/ from sage import *

Answered By: bachi rafik
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.