Claude Code for Mojo: Python Superset with Systems-Level Performance — Claude Skills 360 Blog
Blog / AI / Claude Code for Mojo: Python Superset with Systems-Level Performance
AI

Claude Code for Mojo: Python Superset with Systems-Level Performance

Published: January 11, 2027
Read time: 9 min read
By: Claude Skills 360

Mojo is a Python superset targeting AI infrastructure: the same syntax, full Python interop, but with fn functions that compile to LLVM and run at C++ speed. struct is a stack-allocated value type with explicit memory ownership. SIMD types (SIMD[DType.float32, 8]) map directly to hardware vector instructions. Parametric types use alias for compile-time constants. The ownership system (owned, borrowed, inout) eliminates data races without a garbage collector. Python objects interop via PythonObject — gradually migrate hot paths from Python to Mojo. Claude Code generates Mojo structs, SIMD kernels, parametric algorithms, and the Python interop bridges for high-performance AI infrastructure.

CLAUDE.md for Mojo Projects

## Mojo Stack
- Version: Mojo >= 24.4 (via Magic or modular.com)
- Functions: fn for compiled (type-checked, no implicit conversion), def for Python-compatible
- Types: struct (value, stack), class (reference, heap), Int/Float32/Bool (primitives)
- SIMD: SIMD[DType.float32, 8] for vectorized math
- Ownership: borrowed (read-only ref), inout (mutable ref), owned (move semantics)
- Python interop: from python import numpy as np — PythonObject wraps Python values
- Testing: mojo test or pytest with Mojo extension

fn Functions vs def Functions

# src/basics.mojo — core Mojo patterns

# fn: fully compiled, strict type checking, no implicit conversion
fn add(x: Int, y: Int) -> Int:
    return x + y

# fn with borrowed reference — zero-copy read access
fn sum_list(borrowed data: List[Float32]) -> Float32:
    var total: Float32 = 0.0
    for value in data:
        total += value[]
    return total

# fn with inout — mutates caller's value in-place (no copy)
fn normalize_inout(inout data: List[Float32]) -> None:
    var total: Float32 = 0.0
    for value in data:
        total += value[]
    if total == 0.0:
        return
    for i in range(len(data)):
        data[i] /= total

# fn with owned — takes ownership, caller loses access
fn consume_and_process(owned data: List[Float32]) -> Float32:
    normalize_inout(data)   # Mutate owned copy
    return sum_list(data)

# def: Python-compatible, dynamic, can raise
def load_file(path: String) raises -> String:
    with open(path, "r") as f:
        return f.read()

# Generic parametric function — specialized at compile time
fn max_of[T: Comparable](a: T, b: T) -> T:
    if a > b:
        return a
    return b

# Usage: T inferred from arguments
let bigger = max_of(3.14, 2.71)     # T = Float64
let bigger_int = max_of(42, 17)     # T = Int

Structs

# src/models/order.mojo — value types with Mojo structs

@value  # auto-generates __copyinit__, __moveinit__, __init__
struct Money:
    var cents: Int64
    var currency: String

    fn __init__(inout self, cents: Int64, currency: String = "USD"):
        self.cents = cents
        self.currency = currency

    fn __add__(self, other: Money) raises -> Money:
        if self.currency != other.currency:
            raise Error("Currency mismatch: " + self.currency + " vs " + other.currency)
        return Money(self.cents + other.cents, self.currency)

    fn __lt__(self, other: Money) -> Bool:
        return self.cents < other.cents

    fn formatted(self) -> String:
        let dollars = self.cents // 100
        let remainder = self.cents % 100
        return "$" + str(dollars) + "." + str(remainder).rjust(2, "0")


@value
struct OrderItem:
    var product_id: String
    var product_name: String
    var quantity: Int32
    var unit_price: Money

    fn subtotal(self) -> Money:
        return Money(self.unit_price.cents * Int64(self.quantity))


struct Order:
    var id: String
    var customer_id: String
    var items: List[OrderItem]
    var status: String

    fn __init__(
        inout self,
        id: String,
        customer_id: String,
        items: List[OrderItem],
    ):
        self.id = id
        self.customer_id = customer_id
        self.items = items
        self.status = "pending"

    fn total(self) -> Money:
        var acc = Money(0)
        for item_ref in self.items:
            acc = acc + item_ref[].subtotal()
        return acc

    fn is_high_value(self) -> Bool:
        return self.total().cents > 100_000  # $1000

    fn item_count(self) -> Int:
        var count: Int = 0
        for item_ref in self.items:
            count += Int(item_ref[].quantity)
        return count

SIMD Vectorization

# src/compute/simd_ops.mojo — hardware SIMD acceleration
from sys.info import simdwidthof
from math import sqrt

alias FLOAT_TYPE = DType.float32
alias SIMD_WIDTH = simdwidthof[FLOAT_TYPE]()  # Hardware SIMD width (e.g. 8 for AVX)

# Process 8 floats at once with AVX instructions
fn dot_product_simd(a: DTypePointer[DType.float32], b: DTypePointer[DType.float32], n: Int) -> Float32:
    """SIMD dot product — processes SIMD_WIDTH elements per iteration."""
    var sum = SIMD[FLOAT_TYPE, SIMD_WIDTH](0)
    let simd_end = n - (n % SIMD_WIDTH)

    # Vectorized loop — compiles to AVX/SSE instructions
    for i in range(0, simd_end, SIMD_WIDTH):
        let va = SIMD[FLOAT_TYPE, SIMD_WIDTH].load(a, i)
        let vb = SIMD[FLOAT_TYPE, SIMD_WIDTH].load(b, i)
        sum = sum.fma(va, vb)  # Fused multiply-add: sum += va * vb

    # Handle remainder elements
    var scalar_sum: Float32 = sum.reduce_add()
    for i in range(simd_end, n):
        scalar_sum += a[i] * b[i]

    return scalar_sum


# Vectorized L2 normalization
fn normalize_l2_simd(inout data: DTypePointer[DType.float32], n: Int) -> None:
    """Normalize a vector to unit length using SIMD."""
    # Compute norm using dot product
    let norm_sq = dot_product_simd(data, data, n)
    let norm = sqrt(norm_sq)

    if norm < 1e-8:
        return

    let inv_norm: Float32 = 1.0 / norm
    let simd_end = n - (n % SIMD_WIDTH)

    # Scale all elements
    for i in range(0, simd_end, SIMD_WIDTH):
        let v = SIMD[FLOAT_TYPE, SIMD_WIDTH].load(data, i)
        (v * inv_norm).store(data, i)

    for i in range(simd_end, n):
        data[i] *= inv_norm


# Softmax with SIMD
fn softmax_simd(inout x: DTypePointer[DType.float32], n: Int) -> None:
    """Numerically stable softmax implementation with SIMD."""
    # Find max for numerical stability
    var max_val = x[0]
    for i in range(1, n):
        if x[i] > max_val:
            max_val = x[i]

    # exp(x - max) and sum
    var sum: Float32 = 0.0
    for i in range(n):
        x[i] = math.exp(x[i] - max_val)
        sum += x[i]

    let inv_sum = 1.0 / sum
    for i in range(n):
        x[i] *= inv_sum

Parametric Types

# src/containers/typed_stack.mojo — generic containers with alias
struct Stack[ElementType: AnyType]:
    """Generic stack — specialized at compile time for each ElementType."""
    var data: List[ElementType]

    fn __init__(inout self):
        self.data = List[ElementType]()

    fn push(inout self, owned item: ElementType) -> None:
        self.data.append(item^)  # ^ transfers ownership

    fn pop(inout self) raises -> ElementType:
        if len(self.data) == 0:
            raise Error("Stack is empty")
        return self.data.pop()

    fn peek(self) raises -> ref [__lifetime_of(self)] ElementType:
        if len(self.data) == 0:
            raise Error("Stack is empty")
        return self.data[len(self.data) - 1]

    fn is_empty(self) -> Bool:
        return len(self.data) == 0

    fn size(self) -> Int:
        return len(self.data)


# Parametric function with constraints
fn find_min[T: Comparable & Copyable](borrowed data: List[T]) raises -> T:
    if len(data) == 0:
        raise Error("Cannot find min of empty list")
    var minimum = data[0]
    for i in range(1, len(data)):
        if data[i] < minimum:
            minimum = data[i]
    return minimum

Python Interop

# src/interop/numpy_bridge.mojo — use Python libraries from Mojo
from python import Python, PythonObject

fn compute_with_numpy(data: List[Float32]) raises -> Float32:
    """Use NumPy from Mojo for matrix operations."""
    let np = Python.import_module("numpy")

    # Convert Mojo list to NumPy array
    let py_list = Python.list()
    for val in data:
        py_list.append(val[].cast[DType.float64]())

    let arr = np.array(py_list, dtype=np.float32)

    # NumPy operations return PythonObject
    let result: PythonObject = np.mean(arr)

    # Convert back to Mojo type
    return result.to_float64().cast[DType.float32]()


fn load_model_weights(path: String) raises -> List[Float32]:
    """Load PyTorch model weights via Python interop."""
    let torch = Python.import_module("torch")

    let state_dict = torch.load(path, map_location="cpu")
    let first_weight = state_dict.values().__iter__().__next__()
    let flat = first_weight.flatten()

    var weights = List[Float32]()
    for i in range(int(flat.numel())):
        weights.append(flat[i].item().to_float64().cast[DType.float32]())

    return weights

For the Python data science ecosystem that Mojo is designed to accelerate and interoperate with, see the Python data science guide for NumPy, pandas, and scikit-learn patterns. For the Zig systems language that also eliminates GC and provides explicit memory control without a Python heritage, see the Zig guide for comptime generics and C interop. The Claude Skills 360 bundle includes Mojo skill sets covering SIMD kernels, parametric types, and Python interop bridges. Start with the free tier to try Mojo program generation.

Keep Reading

AI

Claude Code for email.contentmanager: Python Email Content Accessors

Read and write EmailMessage body content with Python's email.contentmanager module and Claude Code — email contentmanager ContentManager for the class that maps content types to get and set handler functions allowing EmailMessage to support get_content and set_content with type-specific behaviour, email contentmanager raw_data_manager for the ContentManager instance that handles raw bytes and str payloads without any conversion, email contentmanager content_manager for the standard ContentManager instance used by email.policy.default that intelligently handles text plain text html multipart and binary content types, email contentmanager get_content_text for the handler that returns the decoded text payload of a text-star message part as a str, email contentmanager get_content_binary for the handler that returns the raw decoded bytes payload of a non-text message part, email contentmanager get_data_manager for the get-handler lookup used by EmailMessage get_content to find the right reader function for the content type, email contentmanager set_content text for the handler that creates and sets a text part correctly choosing charset and transfer encoding, email contentmanager set_content bytes for the handler that creates and sets a binary part with base64 encoding and optional filename Content-Disposition, email contentmanager EmailMessage get_content for the method that reads the message body using the registered content manager handlers, email contentmanager EmailMessage set_content for the method that sets the message body and MIME headers in one call, email contentmanager EmailMessage make_alternative make_mixed make_related for the methods that convert a simple message into a multipart container, email contentmanager EmailMessage add_attachment for the method that attaches a file or bytes to a multipart message, and email contentmanager integration with email.message and email.policy and email.mime and io for building high-level email readers attachment extractors text body accessors HTML readers and policy-aware MIME construction pipelines.

5 min read Feb 12, 2029
AI

Claude Code for email.charset: Python Email Charset Encoding

Control header and body encoding for international email with Python's email.charset module and Claude Code — email charset Charset for the class that wraps a character set name with the encoding rules for header encoding and body encoding describing how to encode text for that charset in email messages, email charset Charset header_encoding for the attribute specifying whether headers using this charset should use QP quoted-printable encoding BASE64 encoding or no encoding, email charset Charset body_encoding for the attribute specifying the Content-Transfer-Encoding to use for message bodies in this charset such as QP or BASE64, email charset Charset output_codec for the attribute giving the Python codec name used to encode the string to bytes for the wire format, email charset Charset input_codec for the attribute giving the Python codec name used to decode incoming bytes to str, email charset Charset get_output_charset for returning the output charset name, email charset Charset header_encode for encoding a header string using the charset's header_encoding method, email charset Charset body_encode for encoding body content using the charset's body_encoding, email charset Charset convert for converting a string from the input_codec to the output_codec, email charset add_charset for registering a new charset with custom encoding rules in the global charset registry, email charset add_alias for adding an alias name that maps to an existing registered charset, email charset add_codec for registering a codec name mapping for use by the charset machinery, and email charset integration with email.message and email.mime and email.policy and email.encoders for building international email senders non-ASCII header encoders Content-Transfer-Encoding selectors charset-aware message constructors and MIME encoding pipelines.

5 min read Feb 11, 2029
AI

Claude Code for email.utils: Python Email Address and Header Utilities

Parse and format RFC 2822 email addresses and dates with Python's email.utils module and Claude Code — email utils parseaddr for splitting a display-name plus angle-bracket address string into a realname and email address tuple, email utils formataddr for combining a realname and address string into a properly quoted RFC 2822 address with angle brackets, email utils getaddresses for parsing a list of raw address header strings each potentially containing multiple comma-separated addresses into a list of realname address tuples, email utils parsedate for parsing an RFC 2822 date string into a nine-tuple compatible with time.mktime, email utils parsedate_tz for parsing an RFC 2822 date string into a ten-tuple that includes the UTC offset timezone in seconds, email utils parsedate_to_datetime for parsing an RFC 2822 date string into an aware datetime object with timezone, email utils formatdate for formatting a POSIX timestamp or the current time as an RFC 2822 date string with optional usegmt and localtime flags, email utils format_datetime for formatting a datetime object as an RFC 2822 date string, email utils make_msgid for generating a globally unique Message-ID string with optional idstring and domain components, email utils decode_rfc2231 for decoding an RFC 2231 encoded parameter value into a tuple of charset language and value, email utils encode_rfc2231 for encoding a string as an RFC 2231 encoded parameter value, email utils collapse_rfc2231_value for collapsing a decoded RFC 2231 tuple to a Unicode string, and email utils integration with email.message and email.headerregistry and datetime and time for building address parsers date formatters message-id generators header extractors and RFC-compliant email construction utilities.

5 min read Feb 10, 2029

Put these ideas into practice

Claude Skills 360 gives you production-ready skills for everything in this article — and 2,350+ more. Start free or go all-in.

Back to Blog

Get 360 skills free