Skip to main content
Log in

Mojo struct

Python

struct Python

Provides methods that help you use Python code in Mojo.

Implemented traits

AnyType, UnknownDestructibility

Methods

__init__

__init__(out self)

Default constructor.

__copyinit__

__copyinit__(out self, existing: Self)

Copy constructor.

Args:

  • existing (Self): The existing instance to copy from.

cpython

cpython(self) -> ref [StaticConstantOrigin] CPython

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

Returns:

Handle to the CPython interpreter instance in the current process.

eval

eval(self, owned code: String) -> Bool

Executes the given Python code.

Args:

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

Returns:

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

evaluate

static evaluate(owned expr: String, file: Bool = False, name: StringSlice[StaticConstantOrigin] = __init__[__mlir_type.!kgen.string]("__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 (StringSlice[StaticConstantOrigin]): The name of the module (most relevant if file is True).

Returns:

PythonObject containing the result of the evaluation.

add_to_path

static add_to_path(dir_path: StringSlice[origin])

Adds a directory to the Python path.

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

from 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)
from 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 (StringSlice[origin]): The path to a Python module you want to import.

import_module

static import_module(owned 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 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))
from 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:

The Python module.

create_module

static create_module(name: StringSlice[StaticConstantOrigin]) -> TypedPythonObject[__init__[__mlir_type.!kgen.string]("Module")]

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:

  • name (StringSlice[StaticConstantOrigin]): The Python module name.

Returns:

The Python module.

add_functions

static add_functions(module: TypedPythonObject[__init__[__mlir_type.!kgen.string]("Module")], owned functions: List[PyMethodDef])

Adds functions to a PythonModule object.

Args:

  • module (TypedPythonObject[__init__[__mlir_type.!kgen.string]("Module")]): The PythonModule object.
  • functions (List[PyMethodDef]): List of function data.

Raises:

If we fail to add the functions to the module.

add_object

static add_object(module: TypedPythonObject[__init__[__mlir_type.!kgen.string]("Module")], owned 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 (TypedPythonObject[__init__[__mlir_type.!kgen.string]("Module")]): The Python module to modify.
  • name (String): The name of the new object.
  • value (PythonObject): The python object value.

dict

static dict[V: PythonConvertible & Copyable & Movable = PythonObject](*, owned **kwargs: V) -> PythonObject

Construct an Python dictionary from keyword arguments.

Parameters:

  • V (PythonConvertible & Copyable & Movable): The type of the values in the dictionary. Must implement the PythonConvertible, Copyable, and Movable traits.

Args:

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

Returns:

The constructed Python dictionary.

Raises:

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

static dict[K: PythonConvertible & Copyable & Movable = PythonObject, V: PythonConvertible & Copyable & Movable = PythonObject](tuples: Span[Tuple[K, V], origin]) -> PythonObject

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

Parameters:

  • K (PythonConvertible & Copyable & Movable): The type of the keys in the dictionary. Must implement the PythonConvertible, Copyable, and Movable traits.
  • V (PythonConvertible & Copyable & Movable): The type of the values in the dictionary. Must implement the PythonConvertible, Copyable, and Movable traits.

Args:

  • tuples (Span[Tuple[K, V], origin]): The list of key-value tuples to construct the dictionary with.

Returns:

The constructed Python dictionary.

Raises:

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

list

static list[T: PythonConvertible & Copyable & Movable](values: Span[T, origin]) -> PythonObject

Initialize the object from a list of values.

Parameters:

  • T (PythonConvertible & Copyable & Movable): The span element type.

Args:

  • values (Span[T, origin]): The values to initialize the list with.

Returns:

A PythonObject representing the list.

static list[*Ts: PythonConvertible](*values: *Ts) -> PythonObject

Construct an Python list of objects.

Parameters:

  • *Ts (PythonConvertible): The list element types.

Args:

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

Returns:

The constructed Python list.

tuple

static tuple[*Ts: PythonConvertible](*values: *Ts) -> PythonObject

Construct an Python tuple of objects.

Parameters:

  • *Ts (PythonConvertible): The list element types.

Args:

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

Returns:

The constructed Python tuple.

as_string_slice

as_string_slice(self, str_obj: PythonObject) -> StringSlice[MutableAnyOrigin]

Return a string representing the given Python object.

Args:

  • str_obj (PythonObject): The Python object.

Returns:

Mojo string representing the given Python object.

is_type

static is_type(x: PythonObject, y: PythonObject) -> Bool

Test if the x object is the y object, the same as x is y in Python.

Args:

  • x (PythonObject): The left-hand-side value in the comparison.
  • y (PythonObject): The right-hand-side type value in the comparison.

Returns:

True if x and y are the same object and False otherwise.

type

static type(obj: PythonObject) -> PythonObject

Return Type of this PythonObject.

Args:

  • obj (PythonObject): PythonObject we want the type of.

Returns:

A PythonObject that holds the type object.

none

static none() -> PythonObject

Get a PythonObject representing None.

Returns:

PythonObject representing None.

str

static str(obj: PythonObject) -> PythonObject

Convert a PythonObject to a Python str.

Args:

  • obj (PythonObject): The PythonObject to convert.

Returns:

A Python str object.

Raises:

An error if the conversion failed.

int

static int(obj: PythonObject) -> PythonObject

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

Args:

  • obj (PythonObject): The PythonObject to convert.

Returns:

A PythonObject representing the result of the conversion to int.

Raises:

If the conversion to int fails.

py_long_as_ssize_t

static py_long_as_ssize_t(obj: PythonObject) -> Int

Get the value of a Python long object.

Args:

  • obj (PythonObject): The Python long object.

Returns:

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 is_true(obj: PythonObject) -> Bool

Check if the PythonObject is truthy.

Args:

  • obj (PythonObject): The PythonObject to check.

Returns:

True if the PythonObject is truthy and False otherwise.

Raises:

If the boolean value of the PythonObject cannot be determined.