pythonsage

Using 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 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.


Solution

  • 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.