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: Nightly
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).

PythonObject

struct PythonObject

A Python object.

Implemented traits

AnyType, Boolable, Copyable, Defaultable, Identifiable, ImplicitlyCopyable, ImplicitlyDeletable, Movable, RegisterPassable, SizedRaising, Writable

Methods

__init__

def __init__() -> Self

Initialize the object with a None value.

def __init__(*, from_owned: PyObjectPtr) -> Self

Initialize this object from an owned reference-counted Python object pointer.

For example, this function should be used to construct a PythonObject from the pointer returned by "New reference"-type objects from the CPython API.

References:

Args:

  • from_owned (PyObjectPtr): An owned pointer to a Python object.

def __init__(*, from_borrowed: PyObjectPtr) -> Self

Initialize this object from a borrowed reference-counted Python object pointer.

For example, this function should be used to construct a PythonObject from the pointer returned by "Borrowed reference"-type objects from the CPython API.

References:

Args:

  • from_borrowed (PyObjectPtr): A borrowed pointer to a Python object.

@implicit def __init__(out self, var source: T)

Initialize this object from a value of some type that can be custom converted to a PythonObject.

Args:

  • source (T): The value to convert to a PythonObject.

Raises:

If the conversion to a PythonObject fails.

def __init__[T: Movable & ImplicitlyDeletable](out self, *, var alloc: T)

Allocate a new PythonObject and store a Mojo value in it.

The newly allocated Python object will contain the provided Mojo T instance directly, without attempting conversion to an equivalent Python builtin type.

Only Mojo types that have a registered Python 'type' object can be stored as a Python object. Mojo types are registered using a PythonTypeBuilder.

Parameters:

Args:

  • alloc (T): The Mojo value to store in the new Python object.

Raises:

If no Python type object has been registered for T by a PythonTypeBuilder.

def __init__(none: NoneType) -> Self

Initialize a none value object from a None literal.

Args:

@implicit def __init__(value: Bool) -> Self

Initialize the object from a bool.

Args:

  • value (Bool): The boolean value.

@implicit def __init__[dtype: DType](value: Scalar[dtype]) -> Self

Initialize the object with a generic scalar value. If the scalar value type is bool, it is converted to a boolean. Otherwise, it is converted to the appropriate integer or floating point type.

Parameters:

  • dtype (DType): The scalar value type.

Args:

@implicit def __init__(out self, string: StringSlice)

Initialize the object from a string.

Args:

Raises:

If the string is not valid UTF-8.

@implicit def __init__(out self, value: StringLiteral)

Initialize the object from a string literal.

Args:

Raises:

If the string is not valid UTF-8.

@implicit def __init__(out self, value: String)

Initialize the object from a string.

Args:

  • value (String): The string value.

Raises:

If the string is not valid UTF-8.

@implicit def __init__(slice: Slice) -> Self

Initialize the object from a Mojo Slice.

Args:

  • slice (Slice): The dictionary value.

def __init__(out self, var *values: Self, *, __list_literal__: NoneType)

Construct an Python list of objects.

Args:

  • *values (Self): The values to initialize the list with.
  • list_literal (NoneType): Tell Mojo to use this method for list literals.

Returns:

Self: The constructed Python list.

Raises:

If the list construction fails.

def __init__(out self, var *values: Self, *, __set_literal__: NoneType)

Construct an Python set of objects.

Args:

  • *values (Self): The values to initialize the set with.
  • set_literal (NoneType): Tell Mojo to use this method for set literals.

Returns:

Self: The constructed Python set.

Raises:

If adding an element to the set fails.

def __init__(out self, var keys: List[Self], var values: List[Self], __dict_literal__: NoneType)

Construct a Python dictionary from a list of keys and a list of values.

Args:

  • keys (List[Self]): The keys of the dictionary.
  • values (List[Self]): The values of the dictionary.
  • dict_literal (NoneType): Tell Mojo to use this method for dict literals.

Raises:

If setting a dictionary item fails.

def __init__(*, copy: Self) -> Self

Copy the object.

This increments the underlying refcount of the existing object.

Args:

  • copy (Self): The value to copy.

__del__

def __del__(deinit self)

Destroy the object.

Decrements the underlying refcount of the pointed-to object. Safe to call from any thread; the GIL is acquired if not already held.

__bool__

def __bool__(self) -> Bool

Evaluate the boolean value of the object.

Returns:

Bool: Whether the object evaluates as true.

__getitem__

def __getitem__(self, *args: Self) -> Self

Return the value for the given key or keys.

Args:

  • *args (Self): The key or keys to access on this object.

Returns:

Self: The value corresponding to the given key for this object.

Raises:

If the index is out of bounds or the key does not exist.

def __getitem__(self, *args: Slice) -> Self

Return the sliced value for the given Slice or Slices.

Args:

  • *args (Slice): The Slice or Slices to apply to this object.

Returns:

Self: The sliced value corresponding to the given Slice(s) for this object.

Raises:

If the index is out of bounds or the key does not exist.

__setitem__

def __setitem__(self, *args: Self, *, var value: Self)

Set the value with the given key or keys.

Args:

  • *args (Self): The key or keys to set on this object.
  • value (Self): The value to set.

Raises:

If setting the item fails.

__neg__

def __neg__(self) -> Self

Negative.

Calls the underlying object's __neg__ method.

Returns:

Self: The result of prefixing this object with a - operator. For most numerical objects, this returns the negative.

Raises:

If the call fails.

__pos__

def __pos__(self) -> Self

Positive.

Calls the underlying object's __pos__ method.

Returns:

Self: The result of prefixing this object with a + operator. For most numerical objects, this does nothing.

Raises:

If the operation fails.

__invert__

def __invert__(self) -> Self

Inversion.

Calls the underlying object's __invert__ method.

Returns:

Self: The logical inverse of this object: a bitwise representation where all bits are flipped, from zero to one, and from one to zero.

Raises:

If the call fails.

__lt__

def __lt__(self, var rhs: Self) -> Self

Less than (rich) comparison operator.

Args:

  • rhs (Self): The value of the right hand side of the comparison.

Returns:

Self: The result of the comparison, not necessarily a boolean.

Raises:

If the object doesn't implement the __lt__ method, or if it fails.

__le__

def __le__(self, var rhs: Self) -> Self

Less than or equal (rich) comparison operator.

Args:

  • rhs (Self): The value of the right hand side of the comparison.

Returns:

Self: The result of the comparison, not necessarily a boolean.

Raises:

If the object doesn't implement the __le__ method, or if it fails.

__eq__

def __eq__(self, var rhs: Self) -> Self

Equality (rich) comparison operator.

Args:

  • rhs (Self): The value of the right hand side of the comparison.

Returns:

Self: The result of the comparison, not necessarily a boolean.

Raises:

If the object doesn't implement the __eq__ method, or if it fails.

__ne__

def __ne__(self, var rhs: Self) -> Self

Inequality (rich) comparison operator.

Args:

  • rhs (Self): The value of the right hand side of the comparison.

Returns:

Self: The result of the comparison, not necessarily a boolean.

Raises:

If the object doesn't implement the __ne__ method, or if it fails.

__gt__

def __gt__(self, var rhs: Self) -> Self

Greater than (rich) comparison operator.

Args:

  • rhs (Self): The value of the right hand side of the comparison.

Returns:

Self: The result of the comparison, not necessarily a boolean.

Raises:

If the object doesn't implement the __gt__ method, or if it fails.

__ge__

def __ge__(self, var rhs: Self) -> Self

Greater than or equal (rich) comparison operator.

Args:

  • rhs (Self): The value of the right hand side of the comparison.

Returns:

Self: The result of the comparison, not necessarily a boolean.

Raises:

If the object doesn't implement the __ge__ method, or if it fails.

__is__

def __is__(self, other: Self) -> Bool

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

Args:

  • other (Self): The right-hand-side value in the comparison.

Returns:

Bool: True if they are the same object and False otherwise.

__contains__

def __contains__(self, var rhs: Self) -> Bool

Contains dunder.

Calls the underlying object's __contains__ method.

Args:

  • rhs (Self): Right hand value.

Returns:

Bool: True if rhs is in self.

Raises:

If the operation fails.

__add__

def __add__(self, var rhs: Self) -> Self

Addition and concatenation.

Calls the underlying object's __add__ method.

Args:

  • rhs (Self): Right hand value.

Returns:

Self: The sum or concatenated values.

Raises:

If the operation is not supported.

__sub__

def __sub__(self, var rhs: Self) -> Self

Subtraction.

Calls the underlying object's __sub__ method.

Args:

  • rhs (Self): Right hand value.

Returns:

Self: The difference.

Raises:

If the operation is not supported.

__mul__

def __mul__(self, var rhs: Self) -> Self

Multiplication.

Calls the underlying object's __mul__ method.

Args:

  • rhs (Self): Right hand value.

Returns:

Self: The product.

Raises:

If the operation is not supported.

__truediv__

def __truediv__(self, var rhs: Self) -> Self

Division.

Calls the underlying object's __truediv__ method.

Args:

  • rhs (Self): The right-hand-side value by which this object is divided.

Returns:

Self: The result of dividing the right-hand-side value by this.

Raises:

If the operation fails.

__floordiv__

def __floordiv__(self, var rhs: Self) -> Self

Return the division of self and rhs rounded down to the nearest integer.

Calls the underlying object's __floordiv__ method.

Args:

  • rhs (Self): The right-hand-side value by which this object is divided.

Returns:

Self: The result of dividing this by the right-hand-side value, modulo any remainder.

Raises:

If the operation fails.

__mod__

def __mod__(self, var rhs: Self) -> Self

Return the remainder of self divided by rhs.

Calls the underlying object's __mod__ method.

Args:

  • rhs (Self): The value to divide on.

Returns:

Self: The remainder of dividing self by rhs.

Raises:

If the operation fails.

__pow__

def __pow__(self, var exp: Self) -> Self

Raises this object to the power of the given value.

Args:

  • exp (Self): The exponent.

Returns:

Self: The result of raising this by the given exponent.

Raises:

If the operation fails.

__lshift__

def __lshift__(self, var rhs: Self) -> Self

Bitwise left shift.

Args:

  • rhs (Self): The right-hand-side value by which this object is bitwise shifted to the left.

Returns:

Self: This value, shifted left by the given value.

Raises:

If the operation fails.

__rshift__

def __rshift__(self, var rhs: Self) -> Self

Bitwise right shift.

Args:

  • rhs (Self): The right-hand-side value by which this object is bitwise shifted to the right.

Returns:

Self: This value, shifted right by the given value.

Raises:

If the operation fails.

__and__

def __and__(self, var rhs: Self) -> Self

Bitwise AND.

Args:

  • rhs (Self): The right-hand-side value with which this object is bitwise AND'ed.

Returns:

Self: The bitwise AND result of this and the given value.

Raises:

If the operation fails.

__or__

def __or__(self, var rhs: Self) -> Self

Bitwise OR.

Args:

  • rhs (Self): The right-hand-side value with which this object is bitwise OR'ed.

Returns:

Self: The bitwise OR result of this and the given value.

Raises:

If the operation fails.

__xor__

def __xor__(self, var rhs: Self) -> Self

Exclusive OR.

Args:

  • rhs (Self): The right-hand-side value with which this object is exclusive OR'ed.

Returns:

Self: The exclusive OR result of this and the given value.

Raises:

If the operation fails.

__radd__

def __radd__(self, var lhs: Self) -> Self

Reverse addition and concatenation.

Calls the underlying object's __radd__ method.

Args:

  • lhs (Self): The left-hand-side value to which this object is added or concatenated.

Returns:

Self: The sum.

Raises:

If the operation is not supported.

__rsub__

def __rsub__(self, var lhs: Self) -> Self

Reverse subtraction.

Calls the underlying object's __rsub__ method.

Args:

  • lhs (Self): The left-hand-side value from which this object is subtracted.

Returns:

Self: The result of subtracting this from the given value.

Raises:

If the operation is not supported.

__rmul__

def __rmul__(self, var lhs: Self) -> Self

Reverse multiplication.

Calls the underlying object's __rmul__ method.

Args:

  • lhs (Self): The left-hand-side value that is multiplied by this object.

Returns:

Self: The product of the multiplication.

Raises:

If the operation is not supported.

__rtruediv__

def __rtruediv__(self, var lhs: Self) -> Self

Reverse division.

Calls the underlying object's __rtruediv__ method.

Args:

  • lhs (Self): The left-hand-side value that is divided by this object.

Returns:

Self: The result of dividing the given value by this.

Raises:

If the operation fails.

__rfloordiv__

def __rfloordiv__(self, var lhs: Self) -> Self

Reverse floor division.

Calls the underlying object's __rfloordiv__ method.

Args:

  • lhs (Self): The left-hand-side value that is divided by this object.

Returns:

Self: The result of dividing the given value by this, modulo any remainder.

Raises:

If the operation fails.

__rmod__

def __rmod__(self, var lhs: Self) -> Self

Reverse modulo.

Calls the underlying object's __rmod__ method.

Args:

  • lhs (Self): The left-hand-side value that is divided by this object.

Returns:

Self: The remainder from dividing the given value by this.

Raises:

If the operation fails.

__rpow__

def __rpow__(self, var lhs: Self) -> Self

Reverse power of.

Args:

  • lhs (Self): The number that is raised to the power of this object.

Returns:

Self: The result of raising the given value by this exponent.

Raises:

If the operation fails.

__rlshift__

def __rlshift__(self, var lhs: Self) -> Self

Reverse bitwise left shift.

Args:

  • lhs (Self): The left-hand-side value that is bitwise shifted to the left by this object.

Returns:

Self: The given value, shifted left by this.

Raises:

If the operation fails.

__rrshift__

def __rrshift__(self, var lhs: Self) -> Self

Reverse bitwise right shift.

Args:

  • lhs (Self): The left-hand-side value that is bitwise shifted to the right by this object.

Returns:

Self: The given value, shifted right by this.

Raises:

If the operation fails.

__rand__

def __rand__(self, var lhs: Self) -> Self

Reverse bitwise and.

Args:

  • lhs (Self): The left-hand-side value that is bitwise AND'ed with this object.

Returns:

Self: The bitwise AND result of the given value and this.

Raises:

If the operation fails.

__ror__

def __ror__(self, var lhs: Self) -> Self

Reverse bitwise OR.

Args:

  • lhs (Self): The left-hand-side value that is bitwise OR'ed with this object.

Returns:

Self: The bitwise OR result of the given value and this.

Raises:

If the operation fails.

__rxor__

def __rxor__(self, var lhs: Self) -> Self

Reverse exclusive OR.

Args:

  • lhs (Self): The left-hand-side value that is exclusive OR'ed with this object.

Returns:

Self: The exclusive OR result of the given value and this.

Raises:

If the operation fails.

__iadd__

def __iadd__(mut self, var rhs: Self)

Immediate addition and concatenation.

Args:

  • rhs (Self): The right-hand-side value that is added to this object.

Raises:

If the operation is not supported.

__isub__

def __isub__(mut self, var rhs: Self)

Immediate subtraction.

Args:

  • rhs (Self): The right-hand-side value that is subtracted from this object.

Raises:

If the operation is not supported.

__imul__

def __imul__(mut self, var rhs: Self)

In-place multiplication.

Calls the underlying object's __imul__ method.

Args:

  • rhs (Self): The right-hand-side value by which this object is multiplied.

Raises:

If the operation is not supported.

__itruediv__

def __itruediv__(mut self, var rhs: Self)

Immediate division.

Args:

  • rhs (Self): The value by which this object is divided.

Raises:

If the operation fails.

__ifloordiv__

def __ifloordiv__(mut self, var rhs: Self)

Immediate floor division.

Args:

  • rhs (Self): The value by which this object is divided.

Raises:

If the operation fails.

__imod__

def __imod__(mut self, var rhs: Self)

Immediate modulo.

Args:

  • rhs (Self): The right-hand-side value that is used to divide this object.

Raises:

If the operation fails.

__ipow__

def __ipow__(mut self, var rhs: Self)

Immediate power of.

Args:

  • rhs (Self): The exponent.

Raises:

If the operation fails.

__ilshift__

def __ilshift__(mut self, var rhs: Self)

Immediate bitwise left shift.

Args:

  • rhs (Self): The right-hand-side value by which this object is bitwise shifted to the left.

Raises:

If the operation fails.

__irshift__

def __irshift__(mut self, var rhs: Self)

Immediate bitwise right shift.

Args:

  • rhs (Self): The right-hand-side value by which this object is bitwise shifted to the right.

Raises:

If the operation fails.

__iand__

def __iand__(mut self, var rhs: Self)

Immediate bitwise AND.

Args:

  • rhs (Self): The right-hand-side value with which this object is bitwise AND'ed.

Raises:

If the operation fails.

__ixor__

def __ixor__(mut self, var rhs: Self)

Immediate exclusive OR.

Args:

  • rhs (Self): The right-hand-side value with which this object is exclusive OR'ed.

Raises:

If the operation fails.

__ior__

def __ior__(mut self, var rhs: Self)

Immediate bitwise OR.

Args:

  • rhs (Self): The right-hand-side value with which this object is bitwise OR'ed.

Raises:

If the operation fails.

__iter__

def __iter__(self) -> _PyIter

Iterate over the object.

Returns:

_PyIter: An iterator object.

Raises:

If the object is not iterable.

__getattr__

def __getattr__(self, var name: String) -> Self

Return the value of the object attribute with the given name.

Args:

  • name (String): The name of the object attribute to return.

Returns:

Self: The value of the object attribute with the given name.

Raises:

If the attribute does not exist.

__setattr__

def __setattr__(self, var name: String, var value: Self)

Set the given value for the object attribute with the given name.

Args:

  • name (String): The name of the object attribute to set.
  • value (Self): The new value to be set for that attribute.

Raises:

If setting the attribute fails.

__call__

def __call__(self, *args: Self, *, var **kwargs: Self) -> Self

Call the underlying object as if it were a function.

Args:

  • *args (Self): Positional arguments to the function.
  • **kwargs (Self): Keyword arguments to the function.

Returns:

Self: The return value from the called object. Raises:

If the function cannot be called for any reason.

__len__

def __len__(self) -> Int

Returns the length of the object.

Returns:

Int: The length of the object.

Raises:

If the operation fails.

__hash__

def __hash__(self) -> Int

Returns the hash value of the object.

Returns:

Int: The hash value of the object.

Raises:

If the operation fails.

__int__

def __int__(self) -> Self

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

Returns:

Self: A Python int object.

Raises:

An error if the conversion failed.

__float__

def __float__(self) -> Self

Convert the PythonObject to a Python float object.

Returns:

Self: A Python float object.

Raises:

If the conversion fails.

__str__

def __str__(self) -> Self

Convert the PythonObject to a Python str.

Returns:

Self: A Python str object.

Raises:

An error if the conversion failed.

write_to

def write_to(self, mut writer: T)

Formats this Python object to the provided Writer.

Args:

  • writer (T): The object to write to.

write_repr_to

def write_repr_to(self, mut writer: T)

Writes the repr of this PythonObject to a writer.

Uses Python's repr() to get the representation of the underlying Python object.

Args:

  • writer (T): The object to write to.

steal_data

def steal_data(var self) -> PyObjectPtr

Take ownership of the underlying pointer from the Python object.

Returns:

PyObjectPtr: The underlying data.

unsafe_get_as_pointer

def unsafe_get_as_pointer[dtype: DType](self) -> UnsafePointer[Scalar[dtype], MutAnyOrigin]

Reinterpret a Python integer as a Mojo pointer.

Warning: converting from an integer to a pointer is unsafe! The compiler assumes the resulting pointer DOES NOT alias any Mojo-derived pointer. This is OK if the pointer originates from and is owned by Python, e.g. the data underpinning a torch tensor.

Parameters:

  • dtype (DType): The desired DType of the pointer.

Returns:

UnsafePointer[Scalar[dtype], MutAnyOrigin]: An UnsafePointer for the underlying Python data.

Raises:

If the operation fails.

downcast_value_ptr

def downcast_value_ptr[T: ImplicitlyDeletable](self, *, func: Optional[StringSlice[StaticConstantOrigin]] = None) -> UnsafePointer[T, MutAnyOrigin]

Get a pointer to the expected contained Mojo value of type T.

This method validates that this object actually contains an instance of T, and will raise an error if it does not.

Mojo values are stored as Python objects backed by the PyMojoObject[T] struct.

Parameters:

  • T (ImplicitlyDeletable): The type of the Mojo value that this Python object is expected to contain.

Args:

Returns:

UnsafePointer[T, MutAnyOrigin]: A pointer to the inner Mojo value.

Raises:

If the Python object does not contain an instance of the Mojo T type.

unchecked_downcast_value_ptr

def unchecked_downcast_value_ptr[mut: Bool, origin: Origin[mut=mut], //, T: ImplicitlyDeletable](ref[origin] self) -> UnsafePointer[T, origin]

Get a pointer to the expected Mojo value of type T.

This function assumes that this Python object was allocated as an instance of PyMojoObject[T] and that the Mojo value has been initialized.

Safety:

The user must be certain that this Python object type matches the bound Python type object for T.

Parameters:

Returns:

UnsafePointer[T, origin]: A pointer to the inner Mojo value.