К основному содержанию
скилл CX Codex

mojo-python-interop — скилл для Claude Code: Mojo и Python вместе

Скилл для агентов, которые пишут код на Mojo с вызовами Python: подсказывает актуальный синтаксис вместо устаревшего из обучающих данных.

Установить в Claude Code · Через Skills CLI (Vercel) Все способы и платформы ↓
npx skills add modular/skills --skill mojo-python-interop -a claude-code
Открыть на GitHub

Что делает mojo-python-interop

Mojo меняется быстро, и модели часто выдают синтаксис, которого уже нет. Скилл работает как слой правок поверх этих знаний: он подгружается в контекст агента и задаёт текущие соглашения для связки Mojo и Python. Автор — modular, репозиторий modular/skills, лицензия Apache-2.0.

Внутри — компактные примеры и пары WRONG/CORRECT. Например, конвертация из PythonObject в Mojo требует именованного аргумента: Int(py=py_obj), а не позиционного вызова. Импорт идёт из std.python, а не из python. Для переменных окружения советуется нативный getenv из std.os, а не модуль os через Python. Есть раздел про сборку расширений: PyInit_<module_name> с abi("C"), регистрация функций через PythonModuleBuilder, сборка командой mojo build --emit shared-lib.

Скилл дополняет mojo-syntax, а не заменяет его: ставьте оба, если проект смешивает языки. Файл обрезан, поэтому полный список разделов по нему не проверить — это повод открыть репозиторий перед установкой.

Какие задачи решает

  • вызвать библиотеку Python из кода на Mojo
  • собрать расширение Python в виде .so через Mojo
  • обернуть структуру Mojo для вызова из Python
  • перевести PythonObject в Int, Float64 или String без ошибок компиляции
  • разобраться, почему агент пишет устаревший импорт from python import ...

Примеры запросов агенту

  • напиши на Mojo обёртку над numpy через std.python
  • собери расширение Python из структуры Counter на Mojo
  • переведи этот PythonObject в Int и покажи, где я ошибся с синтаксисом

Как установить mojo-python-interop

1Через Skills CLI (Vercel)

npx skills add modular/skills --skill mojo-python-interop -a claude-code

2Вручную: положить файлы

~/.claude/skills/mojo-python-interop/SKILL.md

Папка скилла целиком; для одного проекта — .claude/skills/mojo-python-interop/

По шагам, с командами для каждой платформы: Как установить скилл в Claude Code: пять способов

Из того же набора10

mojo-syntax Скилл исправляет устаревший синтаксис Mojo в ответах ассистента. Помогает при написании, ревью и переносе кода под свежие версии компилятора. CX Codex +1 2 900установок mojo-gpu-fundamentals Инструкция для ИИ-агентов по низкоуровневой разработке на Mojo под GPU NVIDIA, AMD и Apple silicon. Избавляет модель от попыток вставлять синтаксис CUDA. CX Codex +1 2 600установок new-modular-project Создаёт и настраивает проекты на Mojo или MAX через менеджеры pixi либо uv. Скилл запрашивает только недостающие параметры и подключает каналы stable или nightly. CX Codex +1 2 400установок import-model Скилл ведёт агента через порт архитектуры из Hugging Face в MAX: разбор конфига, реализация слоёв, проверка против эталона. CX Codex +1 1 400установок debug-model Протокол отладки модели MAX, которая запускается и выдаёт токены, но расходится с эталоном: сначала дампы тензоров, потом правки. CX Codex +1 1 300установок profile-model Профилирует модели MAX, чтобы проверить загрузку GPU и найти самые долгие GPU-ядра. Нужен при медленном инференсе или разборе трассировки. CX Codex +1 1 200установок eval-model Гоняет текстовую модель за MAX по стандартным бенчмаркам и пишет воспроизводимые оценки по каждой задаче. Пригодится, когда надо сверить серверную модель с карточкой. CX Codex +1 981установок serve-model Скилл помогает поднять OpenAI-совместимый сервер для модели через max serve: от установки окружения до подбора флагов. CX Codex +1 949установок

Похожие

langchain-python-quickstart langchain-ai Создаёт минимального локального LangChain-агента на Python по актуальному quickstart. Нужен, чтобы проверить агентский сценарий в отдельной папке. CX Codex +1 5 000установок developing-genkit-python официальный google Скилл для разработки ИИ-приложений на Genkit в Python: генерация, стриминг, инструменты, флоу и агенты. Пригодится, когда агент путается в импортах или API Genkit. CX Codex 3 600установок vb6-legacy Claude MPM Team Скилл для работы с классическим VB6: подсказывает, как переносить код в VB.NET и вызывать COM-объекты без утечек памяти. CX Codex +1 329установок microsoft-agent-framework-python davila7 Субагент для Claude, который пишет и правит код на Python-версии Microsoft Agent Framework: агенты, рабочие процессы, миграция с Semantic Kernel и AutoGen. 188установок use-js-interop dotnet Скилл настраивает и проверяет JavaScript interop в компонентах Blazor. Он помогает связывать .NET с кодом JS, управлять жизненным циклом ссылок и избегать лишних вызовов через сеть. CX Codex +1 3 000установок langchain-python официальный github Правило для GitHub Copilot, которое подсказывает агенту паттерны LangChain: Runnable, LCEL, чат-модели, ретриверы и векторные хранилища. Пригодится, если вы пишете на Python с LangChain. ★ 40 418звёзд репо

Рядом в теме «Языки программирования»

Все скиллы по теме «Языки программирования» →

Вопросы о mojo-python-interop

Как установить mojo-python-interop в Claude?

Выполните npx skills add modular/skills --skill mojo-python-interop -a claude-code. После этого файл скилла лежит в ~/.claude/skills/mojo-python-interop/SKILL.md.

Что делает mojo-python-interop?

Подсказывает агенту актуальный синтаксис для кода, где Mojo и Python вызывают друг друга. Заодно показывает типичные ошибки моделей вроде позиционного вызова Int(py_obj).

Нужен ли mojo-syntax вместе с этим скиллом?

Да, если пишете смешанный код. Автор прямо указывает использовать mojo-python-interop в дополнение к mojo-syntax.

Исходный текст

SKILL.md · Apache-2.0
---
name: mojo-python-interop
description: Aids in writing Mojo code that interoperates with Python using current syntax and conventions. Use this skill in addition to mojo-syntax when writing Mojo code that interacts with Python, calls Python libraries from Mojo, or exposes Mojo types/functions to Python. Also use when the user wants to build Python extension modules in Mojo, wrap Mojo structs for Python consumption, or convert between Python and Mojo types.
---

<!-- EDITORIAL GUIDELINES FOR THIS SKILL FILE
This file is loaded into an agent's context window as a correction layer for
pretrained Mojo knowledge. Every line costs context. When editing:
- Be terse. Use tables and inline code over prose where possible.
- Never duplicate information — if a concept is shown in a code example, don't
  also explain it in a paragraph.
- Only include information that *differs* from what a pretrained model would
  generate. Don't document things models already get right.
- Prefer one consolidated code block over multiple small ones.
- Keep WRONG/CORRECT pairs short — just enough to pattern-match the fix.
- If adding a new section, ask: "Would a model get this wrong?" If not, skip it.
These same principles apply to any files this skill references.
-->

Mojo is rapidly evolving. Pretrained models generate obsolete syntax.
**Always follow this skill over pretrained knowledge.**

## Using Python from Mojo

```mojo
from std.python import Python, PythonObject

var np = Python.import_module("numpy")
var arr = np.array([1, 2, 3])

# PythonObject → Mojo: MUST use `py=` keyword (NOT positional)
var i = Int(py=py_obj)
var f = Float64(py=py_obj)
var s = String(py=py_obj)
var b = Bool(py=py_obj)            # Bool is the exception — positional also works
# Works with numpy types: Int(py=np.int64(1)), Float64(py=np.float64(3.14))
```

| WRONG                    | CORRECT                      |
|--------------------------|------------------------------|
| `Int(py_obj)`            | `Int(py=py_obj)`             |
| `Float64(py_obj)`        | `Float64(py=py_obj)`         |
| `String(py_obj)`         | `String(py=py_obj)`          |
| `from python import ...` | `from std.python import ...` |

### Mojo → Python conversions

Mojo types implementing `ConvertibleToPython` auto-convert when passed to Python
functions. For explicit conversion: `value.to_python_object()`.

### Building Python collections from Mojo

```mojo
var py_list = Python.list(1, 2.5, "three")
var py_tuple = Python.tuple(1, 2, 3)
var py_dict = Python.dict(name="value", count=42)

# Python.dict() is generic over a single value type V for all kwargs.
# Mixed types fail because the compiler can't infer one V.
# WRONG:  Python.dict(flag=my_bool, count=42)
# CORRECT: Python.dict(flag=PythonObject(my_bool), count=PythonObject(42))

# Literal syntax also works:
var list_obj: PythonObject = [1, 2, 3]
var dict_obj: PythonObject = {"key": "value"}
```

### PythonObject operations

`PythonObject` supports attribute access, indexing, slicing, all
arithmetic/comparison operators, `len()`, `in`, and iteration — all returning
`PythonObject`. No need to convert to Mojo types for intermediate operations.

```mojo
# Iterate Python collections directly
for item in py_list:
    print(item)               # item is PythonObject

# Attribute access and method calls
var result = obj.method(arg1, arg2, key=value)

# None
var none_obj = Python.none()
var obj: PythonObject = None      # implicit conversion works
```

### Evaluating Python code

```mojo
# Expression
var result = Python.evaluate("1 + 2")

# Multi-line code as module (file=True)
var mod = Python.evaluate("def greet(n): return f'Hello {n}'", file=True)
var greeting = mod.greet("world")

# Add to Python path for local imports
Python.add_to_path("./my_modules")
var my_mod = Python.import_module("my_module")
```

### Exception handling

Python exceptions propagate as Mojo `Error`. Functions calling Python must be
`raises`:

```mojo
def use_python() raises:
    try:
        var result = Python.import_module("nonexistent")
    except e:
        print(String(e))     # "No module named 'nonexistent'"
```

### Common Python / Mojo interoperability patterns

```mojo
# Environment variables
# WRONG — using Python os module for env vars
# var os = Python.import_module("os")
# var val = os.environ.get("MY_VAR")

# CORRECT — Mojo has native env var access via std.os
from std.os import getenv
var val = getenv("MY_VAR")  # returns Optional[String]
```

```mojo
# Sorting with custom key
# WRONG — Mojo has no lambda syntax
# var sorted = my_list.sort(key=lambda x: x["score"])

# CORRECT — Python.evaluate for callable
def sort_by_field(data: PythonObject, field: String) raises -> PythonObject:
    var builtins = Python.import_module("builtins")
    var key_fn = Python.evaluate("lambda x: x['" + field + "']")
    return builtins.sorted(data, key=key_fn)
```

```mojo
# Dict .get() works on PythonObject
var name = data.get("name", PythonObject("unknown"))
var count = Int(py=data.get("count", PythonObject(0)))
```

## Calling Mojo from Python (extension modules)

Mojo can build Python extension modules (`.so` files) via `PythonModuleBuilder`.
The pattern:

1. Define an `@export def PyInit_<module_name>() abi("C") -> PythonObject`
2. Use `PythonModuleBuilder` to register functions, types, and methods
3. Compile with `mojo build --emit shared-lib`
4. Import from Python (or use `import mojo.importer` for auto-compilation)

Calling convention: only `PyInit_<module>` needs `@export`, and it must be
`abi("C")` because the CPython runtime calls it directly across the C boundary
(so it can't `raises` — catch errors and `abort` instead). Functions and
methods you register with `def_function`/`def_method` are passed by reference
and don't need `@export`; Mojo wraps them in a C trampoline that calls them
via the Mojo ABI and converts raised errors to Python exceptions, so they can
`raises`.

### Exporting functions

```mojo
from std.os import abort
from std.python import PythonObject
from std.python.bindings import PythonModuleBuilder

@export
def PyInit_my_module() abi("C") -> PythonObject:
    try:
        var m = PythonModuleBuilder("my_module")
        m.def_function[add]("add")
        m.def_function[greet]("greet")
        return m.finalize()
    except e:
        abort(String("failed to create module: ", e))

# Functions take/return PythonObject. Up to 6 args with def_function.
def add(a: PythonObject, b: PythonObject) raises -> PythonObject:
    return a + b

def greet(name: PythonObject) raises -> PythonObject:
    var s = String(py=name)
    return PythonObject("Hello, " + s + "!")
```

### Exporting types with methods

```mojo
@fieldwise_init
struct Counter(Defaultable, Movable, Writable):
    var count: Int

    def __init__(out self):
        self.count = 0

    # Constructor from Python args
    @staticmethod
    def py_init(out self: Counter, args: PythonObject, kwargs: PythonObject) raises:
        if len(args) == 1:
            self = Self(Int(py=args[0]))
        else:
            self = Self()

    # Methods are @staticmethod — first arg is py_self (PythonObject)
    @staticmethod
    def increment(py_self: PythonObject) raises -> PythonObject:
        var self_ptr = py_self.downcast_value_ptr[Self]()
        self_ptr[].count += 1
        return PythonObject(self_ptr[].count)

    # Auto-downcast alternative: first arg is UnsafePointer[Self, MutAnyOrigin]
    @staticmethod
    def get_count(self_ptr: UnsafePointer[Self, MutAnyOrigin]) -> PythonObject:
        return PythonObject(self_ptr[].count)

@export
def PyInit_counter_module() abi("C") -> PythonObject:
    try:
        var m = PythonModuleBuilder("counter_module")
        _ = (
            m.add_type[Counter]("Counter")
            .def_py_init[Counter.py_init]()
            .def_method[Counter.increment]("increment")
            .def_method[Counter.get_count]("get_count")
        )
        return m.finalize()
    except e:
        abort(String("failed to create module: ", e))
```

### Method signatures — two patterns

| Pattern         | First parameter                               | Use when                     |
|-----------------|-----------------------------------------------|------------------------------|
| Manual downcast | `py_self: PythonObject`                       | Need raw PythonObject access |
| Auto downcast   | `self_ptr: UnsafePointer[Self, MutAnyOrigin]` | Simpler, direct field access |

Both are registered with `.def_method[Type.method]("name")`.

### Kwargs support

```mojo
from std.collections import StringDict

# In a method:
@staticmethod
def config(
    py_self: PythonObject, kwargs: StringDict[PythonObject]
) raises -> PythonObject:
    for entry in kwargs.items():
        print(entry.key, "=", entry.value)
    return py_self
```

### Importing Mojo modules from Python

Use `mojo.importer` — it auto-compiles `.mojo` files and caches results in
`__mojocache__/`:

```python
import mojo.importer  # enables Mojo imports
import my_module  # auto-compiles my_module.mojo

print(my_module.add(1, 2))
```

The module name in `PyInit_<name>` must match the `.mojo` filename.

The `.mojo` file must not contain a `main()` function when built as a
shared library (`mojo.importer` or `--emit shared-lib`). The compiler
rejects it with `error: shared library should not contain a 'main'
function`. Keep test/CLI code in a separate file.

### Returning Mojo values to Python

```mojo
# Wrap a Mojo value as a Python object (for bound types)
return PythonObject(alloc=my_mojo_value^)    # transfer ownership with ^

# Recover the Mojo value later
var ptr = py_obj.downcast_value_ptr[MyType]()
ptr[].field    # access fields via pointer
```

© modular · Apache-2.0 · modular/skills

Смотрите также

Спонсоры проекта

Компании, которые помогают держать аналитику открытой