'Sagemath as a python library

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

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

>>> 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 to embed all the functionalities of sagemath within the python world.



Solution 1:[1]

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.

Solution 2:[2]

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.

Solution 3:[3]

1/ pip install sage
2/ from sage import *

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Samuel Lelièvre
Solution 2
Solution 3 bachi rafik