PythonInterface

Module

Implements Python interoperability.

Python

Provides methods that help you use Python code in Mojo.

Fields:

impl

The underlying implementation of Mojo’s Python interface.

Functions:

__init__

__init__(self: Self&)

Default constructor.

__copyinit__

__copyinit__(self: Self&, existing: Self)

Copy constructor.

Args:

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

__del__

__del__(self: Self)

__str__

__str__(self: Self&, str: PythonObject) -> StringRef

Return a string representing the given Python object.

This function allows to convert Python objects to Mojo string type.

Returns:

Mojo string representing the given Python object.

add_to_path

add_to_path(str: StringRef) -> None

Adds a directory to the Python path.

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

from PythonInterface import Python

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

let c = mypython.my_algorithm(2, 3)

Args:

  • str (StringRef): The path to a Python module you want to import.

dict

dict() -> PythonDictionary

Construct an empty Python dictionary.

Returns:

The constructed empty Python dictionary.

eval

eval(self: Self&, str: StringRef) -> Bool

Executes the given Python code.

Args:

  • str (StringRef): The python code to execute.

Returns:

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

evaluate

evaluate(str: StringRef) -> PythonObject

Executes the given Python code.

Args:

  • str (StringRef): The Python expression to evaluate.

Returns:

PythonObject containing the result of the evaluation.

import_module

import_module(str: StringRef) -> PythonObject

Imports a Python module.

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

from PythonInterface import Python

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

Args:

  • str (StringRef): 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.

is_type

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.

none

none() -> PythonObject

Get a PythonObject representing None.

Returns:

PythonObject representing None.

throw_python_exception_if_error_state

throw_python_exception_if_error_state() -> None

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