IMPORTANT: To view this page as Markdown, append `.md` to the URL (e.g. /docs/manual/basics.md). For the complete Mojo documentation index, see llms.txt.
Skip to main content
Version: 1.0.0
For the complete Mojo documentation index, see llms.txt. Markdown versions of all pages are available by appending .md to any URL (e.g. /docs/manual/basics.md).

Python

struct Python

Provides methods that help you use Python code in Mojo.

Implemented traits

AnyType, Copyable, Defaultable, Deinitable, ImplicitlyCopyable, Movable

Methods

__init__

def __init__(out self)

Construct a new Python instance.

def __init__(out self, ref[ImmStaticOrigin] cpython: CPython)

Construct a Python instance from an existing reference to the lower-level singleton CPython instance.

Args:

  • cpython (CPython): Reference to the CPython singleton.

cpython

def cpython(self) -> ref[ImmStaticOrigin] CPython

Handle to the low-level C API of the CPython interpreter present in the current process.

Returns:

ref[ImmStaticOrigin] CPython: Handle to the CPython interpreter instance in the current process.

eval

def eval(self, var code: String) -> Bool

Executes the given Python code.

Args:

  • code (String): The python code to execute.

Returns:

Bool: True if the code executed successfully or False if the code raised an exception.

evaluate

static def evaluate(var expr: String, file: Bool = False, name: StringSpan[ImmStaticOrigin] = StringSpan("__main__")) -> PythonObject

Executes the given Python code.

Args:

  • expr (String): The Python expression to evaluate.
  • file (Bool): Evaluate as a file and return the module.
  • name (StringSpan[ImmStaticOrigin]): The name of the module (most relevant if file is True).

Returns:

PythonObject: PythonObject containing the result of the evaluation.

Raises:

If the operation fails.

add_to_path

static def add_to_path(dir_path: StringSpan)

Adds a directory to the Python path.

This might be necessary to import a Python module via import_module(). For example:

from std.python import Python

# Specify path to `mypython.py` module
Python.add_to_path("path/to/module")
var mypython = Python.import_module("mypython")

var c = mypython.my_algorithm(2, 3)

Args:

  • dir_path (StringSpan): The path to a Python module you want to import.

Raises:

If the operation fails.

import_module

static def import_module(var module: String) -> PythonObject

Imports a Python module.

This provides you with a module object you can use just like you would in Python. For example:

from std.python import Python

# This is equivalent to Python's `import numpy as np`
np = Python.import_module("numpy")
a = np.array(Python.list(1, 2, 3))

Args:

  • module (String): The Python module name. This module must be visible from the list of available Python paths (you might need to add the module's path with add_to_path()).

Returns:

PythonObject: The Python module.

Raises:

If the operation fails.

create_module

static def create_module(name: StringSpan[ImmStaticOrigin]) -> PythonObject

Creates a Python module using the provided name.

Inspired by https://github.com/pybind/pybind11/blob/a1d00916b26b187e583f3bce39cd59c3b0652c32/include/pybind11/pybind11.h#L1227

TODO: allow specifying a doc-string to attach to the module upon creation or lazily added?

Args:

Returns:

PythonObject: The Python module.

Raises:

If the operation fails.

add_functions

static def add_functions(module: PythonObject, var functions: List[PyMethodDef])

Adds functions to a Python module object.

Args:

Raises:

If we fail to add the functions to the module.

add_object

static def add_object(module: PythonObject, var name: String, value: PythonObject)

Add a new object to module with the given name and value.

The provided object can be any type of Python object: an instance, a type object, a function, etc.

The added value will be inserted into the __dict__ of the provided module.

Args:

  • module (PythonObject): The Python module to modify.
  • name (String): The name of the new object.
  • value (PythonObject): The python object value.

Raises:

If the operation fails.

dict

static def dict(*, var **kwargs: PythonObject) -> PythonObject

Construct an Python dictionary from keyword arguments.

Args:

  • **kwargs (PythonObject): The keyword arguments to construct the dictionary with.

Returns:

PythonObject: The constructed Python dictionary.

Raises:

On failure to construct the dictionary or convert the values to Python objects.

static def dict(tuples: Span[Tuple[PythonObject, PythonObject]]) -> PythonObject

Construct an Python dictionary from a list of key-value tuples.

Args:

Returns:

PythonObject: The constructed Python dictionary.

Raises:

On failure to construct the dictionary or convert the keys or values to Python objects.

list

static def list(values: Span[PythonObject]) -> PythonObject

Initialize the object from a list of values.

Args:

Returns:

PythonObject: A PythonObject representing the list.

Raises:

If the operation fails.

static def list(var *values: PythonObject) -> PythonObject

Construct an Python list of objects.

Args:

  • *values (PythonObject): The values to initialize the list with.

Returns:

PythonObject: The constructed Python list.

Raises:

If the operation fails.

tuple

static def tuple(var *values: PythonObject) -> PythonObject

Construct an Python tuple of objects.

Args:

  • *values (PythonObject): The values to initialize the tuple with.

Returns:

PythonObject: The constructed Python tuple.

Raises:

If the operation fails.

as_string_slice

def as_string_slice(self, obj: PythonObject) -> StringSpan[ImmutAnyOrigin]

Return a string representing the given Python object.

Args:

Returns:

StringSpan[ImmutAnyOrigin]: Mojo string representing the given Python object.

type

static def type(obj: PythonObject) -> PythonObject

Return Type of this PythonObject.

Args:

Returns:

PythonObject: A PythonObject that holds the type object.

none

static def none() -> PythonObject

Get a PythonObject representing None.

Returns:

PythonObject: PythonObject representing None.

str

static def str(obj: PythonObject) -> PythonObject

Convert a PythonObject to a Python str.

Args:

Returns:

PythonObject: A Python str object.

Raises:

An error if the conversion failed.

int

static def int(obj: PythonObject) -> PythonObject

Convert a PythonObject to a Python int (i.e. arbitrary precision integer).

Args:

Returns:

PythonObject: A PythonObject representing the result of the conversion to int.

Raises:

If the conversion to int fails.

float

static def float(obj: PythonObject) -> PythonObject

Convert a PythonObject to a Python float object.

Args:

Returns:

PythonObject: A Python float object.

Raises:

If the conversion fails.

py_long_as_ssize_t

static def py_long_as_ssize_t(obj: PythonObject) -> Py_ssize_t

Get the value of a Python long object.

Args:

Returns:

Py_ssize_t: The value of the long object as a Py_ssize_t.

Raises:

If obj is not a Python long object, or if the long object value overflows Py_ssize_t.

is_true

static def is_true(obj: PythonObject) -> Bool

Check if the PythonObject is truthy.

Args:

Returns:

Bool: True if the PythonObject is truthy and False otherwise.

Raises:

If the boolean value of the PythonObject cannot be determined.