Mojo struct
Python
struct Python
Provides methods that help you use Python code in Mojo.
Implemented traits
AnyType,
Copyable,
Defaultable,
ImplicitlyCopyable,
UnknownDestructibility
Aliases
__copyinit__is_trivial
alias __copyinit__is_trivial = True
__del__is_trivial
alias __del__is_trivial = True
Methods
__init__
__init__(out self)
Construct a new Python instance.
__init__(out self, ref [StaticConstantOrigin] cpython: CPython)
Construct a Python instance from an existing reference to the lower-level singleton CPython instance.
Args:
- cpython (
CPython): Reference to theCPythonsingleton.
cpython
cpython(self) -> ref [StaticConstantOrigin] CPython
Handle to the low-level C API of the CPython interpreter present in the current process.
Returns:
ref: Handle to the CPython interpreter instance in the current process.
eval
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 evaluate(var expr: String, file: Bool = False, name: StringSlice[StaticConstantOrigin] = "__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): The name of the module (most relevant iffileis True).
Returns:
PythonObject: PythonObject containing the result of the evaluation.
Raises:
If the operation fails.
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)Args:
- dir_path (
StringSlice): The path to a Python module you want to import.
Raises:
If the operation fails.
import_module
static 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 python import Python
# This is equivalent to Python's `import numpy as np`
np = Python.import_module("numpy")
a = np.array([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 withadd_to_path()).
Returns:
PythonObject: The Python module.
Raises:
If the operation fails.
create_module
static create_module(name: StringSlice[StaticConstantOrigin]) -> PythonObject
Creates a Python module using the provided name.
TODO: allow specifying a doc-string to attach to the module upon creation or lazily added?
Args:
- name (
StringSlice): The Python module name.
Returns:
PythonObject: The Python module.
Raises:
If the operation fails.
add_functions
static add_functions(module: PythonObject, var functions: List[PyMethodDef])
Adds functions to a Python module object.
Args:
- module (
PythonObject): The Python module object. - functions (
List): List of function data.
Raises:
If we fail to add the functions to the module.
add_object
static 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 dict[V: ConvertibleToPython & Copyable & Movable = PythonObject](*, var **kwargs: V) -> PythonObject
Construct an Python dictionary from keyword arguments.
Parameters:
- V (
ConvertibleToPython&Copyable&Movable): The type of the values in the dictionary. Must implement theConvertibleToPython,Copyable, andMovabletraits.
Args:
- **kwargs (
V): 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 dict[K: ConvertibleToPython & Copyable & Movable = PythonObject, V: ConvertibleToPython & Copyable & Movable = PythonObject](tuples: Span[Tuple[K, V], origin]) -> PythonObject
Construct an Python dictionary from a list of key-value tuples.
Parameters:
- K (
ConvertibleToPython&Copyable&Movable): The type of the keys in the dictionary. Must implement theConvertibleToPython,Copyable, andMovabletraits. - V (
ConvertibleToPython&Copyable&Movable): The type of the values in the dictionary. Must implement theConvertibleToPython,Copyable, andMovabletraits.
Args:
- tuples (
Span): The list of key-value tuples to construct the dictionary with.
Returns:
PythonObject: The constructed Python dictionary.
Raises:
On failure to construct the dictionary or convert the keys or values to Python objects.
list
static list[T: ConvertibleToPython & Copyable & Movable](values: Span[T, origin]) -> PythonObject
Initialize the object from a list of values.
Parameters:
- T (
ConvertibleToPython&Copyable&Movable): The span element type.
Args:
- values (
Span): The values to initialize the list with.
Returns:
PythonObject: A PythonObject representing the list.
Raises:
If the operation fails.
static list[*Ts: ConvertibleToPython & Copyable](var *values: *Ts) -> PythonObject
Construct an Python list of objects.
Parameters:
- *Ts (
ConvertibleToPython&Copyable): The list element types.
Args:
- *values (
*Ts): The values to initialize the list with.
Returns:
PythonObject: The constructed Python list.
Raises:
If the operation fails.
tuple
static tuple[*Ts: ConvertibleToPython & Copyable](var *values: *Ts) -> PythonObject
Construct an Python tuple of objects.
Parameters:
- *Ts (
ConvertibleToPython&Copyable): The list element types.
Args:
- *values (
*Ts): The values to initialize the tuple with.
Returns:
PythonObject: The constructed Python tuple.
Raises:
If the operation fails.
as_string_slice
as_string_slice(self, obj: PythonObject) -> StringSlice[ImmutAnyOrigin]
Return a string representing the given Python object.
Args:
- obj (
PythonObject): The Python object.
Returns:
StringSlice: Mojo string representing the given Python object.
type
static type(obj: PythonObject) -> PythonObject
Return Type of this PythonObject.
Args:
- obj (
PythonObject): PythonObject we want the type of.
Returns:
PythonObject: A PythonObject that holds the type object.
none
static none() -> PythonObject
Get a PythonObject representing None.
Returns:
PythonObject: PythonObject representing None.
str
static str(obj: PythonObject) -> PythonObject
Convert a PythonObject to a Python str.
Args:
- obj (
PythonObject): The PythonObject to convert.
Returns:
PythonObject: A Python str object.
Raises:
An error if the conversion failed.
int
static int(obj: PythonObject) -> PythonObject
Convert a PythonObject to a Python int (i.e. arbitrary precision integer).
Args:
- obj (
PythonObject): The PythonObject to convert.
Returns:
PythonObject: A PythonObject representing the result of the conversion to int.
Raises:
If the conversion to int fails.
float
static float(obj: PythonObject) -> PythonObject
Convert a PythonObject to a Python float object.
Args:
- obj (
PythonObject): The PythonObject to convert.
Returns:
PythonObject: A Python float object.
Raises:
If the conversion 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 Pythonlongobject.
Returns:
Int: 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:
Bool: True if the PythonObject is truthy and False otherwise.
Raises:
If the boolean value of the PythonObject cannot be determined.
Was this page helpful?
Thank you! We'll create more content like this.
Thank you for helping us improve!