Skip to main content
Log in

Mojo struct

Python

struct Python

Provides methods that help you use Python code in Mojo.

Fields

  • impl (_PythonInterfaceImpl): The underlying implementation of Mojo's Python interface.

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.

eval

eval(mut self, code: StringSlice[origin]) -> Bool

Executes the given Python code.

Args:

  • code (StringSlice[origin]): The python code to execute.

Returns:

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

evaluate

static evaluate(expr: StringSlice[origin], file: Bool = False, name: StringSlice[StaticConstantOrigin] = StringSlice("__main__")) -> PythonObject

Executes the given Python code.

Args:

  • expr (StringSlice[origin]): 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(module: StringSlice[origin]) -> 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`
var np = Python.import_module("numpy")
a = np.array([1, 2, 3])
from python import Python

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

Args:

  • module (StringSlice[origin]): 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: String) -> TypedPythonObject["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 (String): The Python module name.

Returns:

The Python module.

add_functions

static add_functions(mut module: TypedPythonObject["Module"], owned functions: List[PyMethodDef])

Adds functions to a PyModule object.

Args:

  • module (TypedPythonObject["Module"]): The PyModule object.
  • functions (List[PyMethodDef]): List of function data.

unsafe_add_methods

static unsafe_add_methods(mut module: TypedPythonObject["Module"], functions: UnsafePointer[PyMethodDef])

Adds methods to a PyModule object.

Safety: The provided functions pointer must point to data that lives for the duration of the associated Python interpreter session.

Args:

  • module (TypedPythonObject["Module"]): The PyModule object.
  • functions (UnsafePointer[PyMethodDef]): A null terminated pointer to function data.

add_object

static add_object(mut module: TypedPythonObject["Module"], name: StringLiteral, 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["Module"]): The Python module to modify.
  • name (StringLiteral): The name of the new object.
  • value (PythonObject): The python object value.

dict

static dict() -> PythonObject

Construct an empty Python dictionary.

Returns:

The constructed empty Python dictionary.

list

static list() -> PythonObject

Construct an empty Python list.

Returns:

The constructed empty Python list.

as_string_slice

as_string_slice(mut 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.

throw_python_exception_if_error_state

static throw_python_exception_if_error_state(mut cpython: CPython)

Raise an exception if CPython interpreter is in an error state.

Args:

  • cpython (CPython): The cpython instance we wish to error check.

unsafe_get_python_exception

static unsafe_get_python_exception(mut cpython: CPython) -> Error

Get the Error object corresponding to the current CPython interpreter error state.

Safety: The caller MUST be sure that the CPython interpreter is in an error state before calling this function.

This function will clear the CPython error.

Args:

  • cpython (CPython): The cpython instance we wish to error check.

Returns:

Error object describing the CPython error.

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.

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.