Python interoperability

Mojo documents Python interoperability through the CPython runtime. Importing a Python module does not mean every Python program compiles unchanged as Mojo. Evaluate that boundary separately from native Mojo code.

Mojo Language Fundamentals

Representative Mojo code:

from math import sqrt
from sys.info import simdwidthof
from algorithm import vectorize

alias float_type = DType.float32
alias simd_width = simdwidthof[float_type]()

fn euclidean_distance(
 a: DTypePointer[float_type],
 b: DTypePointer[float_type],
 n: Int
) -> Float32:
 var sum = SIMD[float_type, simd_width](0)

 @parameter
 fn compute_chunk[simd_width: Int](i: Int):
 let diff = a.load[width=simd_width](i) - b.load[width=simd_width](i)
 sum += diff * diff

 vectorize[compute_chunk, simd_width](n)
 return sqrt(sum.reduce_add())

A few things to unpack:

  1. alias defines compile-time constants. simd_width is resolved at compile time based on your CPU's SIMD register width (4 for SSE, 8 for AVX2, 16 for AVX-512).

  2. SIMD[float_type, simd_width] is an explicit SIMD vector type. When you write a.load[width=simd_width](i), you're loading 8 floats at once into a 256-bit register (on AVX2).

  3. @parameter makes the inner function a compile-time parameter, enabling loop unrolling and specialization.

  4. vectorize is a standard library function that handles the tail loop (when n isn't a multiple of simd_width).

This is not Python with type hints. This is a systems language that looks like Python.

The Ownership Model: Not Rust, Not C++

Mojo has ownership semantics, but they're deliberately simpler than Rust's borrow checker. Three modes:

# `owned` - the function takes ownership, caller can't use the value after
fn consume(owned data: Tensor[float_type]):
 # data is ours, will be destroyed when function ends
 process(data)

# `borrowed` (default) - immutable reference, no copy
fn inspect(data: Tensor[float_type]):
 # data is read-only, still owned by caller
 print(data.shape())

# `inout` - mutable reference
fn modify(inout data: Tensor[float_type]):
 # data can be modified in place
 data *= 2.0

fn main():
 var tensor = Tensor[float_type](1000, 1000)

 inspect(tensor) # borrowed, tensor still valid
 modify(tensor) # inout, tensor modified in place
 consume(tensor^) # owned, tensor moved (^ is the transfer operator)
 # tensor is no longer valid here

The ^ transfer operator is Mojo's version of std::move. It's explicit, you can see every ownership transfer in the code. This is simpler than Rust's implicit moves and explicit borrows, at the cost of less safety. Mojo won't catch use-after-move at compile time in all cases the way Rust does.

Where Mojo Actually Wins

from python import Python
from algorithm import parallelize

fn preprocess_batch(
 texts: PythonObject,
 num_texts: Int
) -> Tensor[DType.float32]:
 var features = Tensor[DType.float32](num_texts, 768)

 @parameter
 fn process_text(i: Int):
 let text = texts[i]
 # Clean text (Mojo string operations)
 var cleaned = text.lower()
 cleaned = remove_special_chars(cleaned)
 cleaned = normalize_unicode(cleaned)

 # Feature hashing (pure Mojo, vectorized)
 let tokens = tokenize_whitespace(cleaned)
 hash_features(tokens, features, i)

 parallelize[process_text](num_texts)
 return features

Custom loss functions and metrics. If you're writing research code with non-standard loss functions, Mojo lets you write them with explicit SIMD without dropping to C++:

fn focal_loss(
 predictions: Tensor[DType.float32],
 targets: Tensor[DType.float32],
 gamma: Float32,
 alpha: Float32,
 n: Int
) -> Float32:
 var total_loss = SIMD[DType.float32, 8](0)

 @parameter
 fn compute[simd_width: Int](i: Int):
 let p = predictions.load[width=simd_width](i)
 let t = targets.load[width=simd_width](i)

 # Focal loss: -alpha * (1-pt)^gamma * log(pt)
 let pt = t * p + (1 - t) * (1 - p)
 let focal_weight = (1 - pt) ** gamma
 let ce = -(t * log(p) + (1 - t) * log(1 - p))
 total_loss += alpha * focal_weight * ce

 vectorize[compute, 8](n)
 return total_loss.reduce_add() / n

The Python Interop: Seamless but Not Free

The interop story is Mojo's biggest selling point and its most misunderstood feature. You can import any Python module:

from python import Python

fn main() raises:
 let np = Python.import_module("numpy")
 let torch = Python.import_module("torch")
 let transformers = Python.import_module("transformers")

 # This works, you're calling Python objects from Mojo
 let model = transformers.AutoModel.from_pretrained("bert-base-uncased")
 let tokenizer = transformers.AutoTokenizer.from_pretrained("bert-base-uncased")

 let inputs = tokenizer("Hello world", return_tensors="pt")
 let outputs = model(**inputs)

 # But this crosses the Python/Mojo boundary
 # Every call has marshalling overhead
 let embeddings = outputs.last_hidden_state.detach().numpy()

 # Convert to Mojo tensor for fast operations
 var mojo_tensor = numpy_to_mojo_tensor(embeddings)
 normalize_embeddings(mojo_tensor, 1, 768)

The array copy is the real cost for large tensors. Mojo can share memory with NumPy arrays (zero-copy), but you need to use DTypePointer and manage the lifetime carefully.

Mojo vs Rust: The Honest Comparison

Here is a direct comparison:

Mojo wins on: Python ecosystem access, ML-specific ergonomics (SIMD types, tensor operations, @parameter metaprogramming), ease of adoption for Python developers.

The real question is: who writes the code? For teams of Python developers building ML infrastructure, Mojo is the path of least resistance. For teams of systems programmers building general-purpose infrastructure, Rust is the better choice. The language capabilities overlap, but the developer experience diverges sharply.

What's Missing

Mojo is pre-1.0 and it shows:

Standard library is sparse. No async runtime, no HTTP client, no database drivers. You call Python for all of that, which works but negates the performance advantage.

Error messages are cryptic. The MLIR-based compiler produces error messages that reference intermediate representations instead of source code. This is improving but still rough.

Debugger support is limited. No stepping debugger of production quality exists yet. Print debugging is the norm.

Package management is nascent. Modular has a package system, but the community package ecosystem is tiny compared to pip or cargo.

Closed-source compiler. The Mojo standard library is open-source, but the compiler is proprietary. This is a significant risk factor for long-term adoption. If Modular goes under, you're stuck.

Assessment

If you're building ML inference servers, custom data pipelines, or numerical computing libraries, Mojo is worth serious evaluation. If you're building web servers, CLI tools, or general-purpose applications, look elsewhere. The ecosystem isn't there yet, and the Python interop overhead means you're not getting Mojo-speed for anything that touches the Python world.

Editorial update (November 10, 2026): unsupported experience claims and numerical outcomes were removed. Examples are instructional.