← 返回技术雷达
Hacker News tech

Libraries Run Rust Inside Python (With PyO3)

Hacker News 热议:Libraries Run Rust Inside Python (With PyO3)(49 赞 / 29 评论,来源 belderbos.dev)

一句话概要

Build a Rust JSON parser into a module Python can import with PyO3, then see what the return trip costs when Rust data becomes Python dicts and lists.

原文开头节选

Every time you validate data with Pydantic v2, the data-validation library most Python apps reach for, a Rust extension does the work. Its core, pydantic-core, is built with PyO3, the same toolchain we’ll use here.

This post builds that same kind of bridge, small enough to read in one sitting: a JSON parser written in Rust, exposed to Python, so you can import it like any other package. The last step, turning the Rust result into Python objects, is the one to understand before you port anything: for a parser like this, it can cost more than the parsing itself.

#[pyfunction] and #[pymodule] are the two Rust macros that do the wiring. A Rust attribute macro is close to a Python decorator: it rewrites the function it sits on, here adding the glue that lets Python call it and handles the type conversions and reference counting at the boundary.

Maturin then compiles the crate to a shared library (.so, .dylib, .dll) and drops it into your virtual environment, so import just works.

(以上为原文节选,完整内容见下方”原文来源”)

这条动态今日登上 Hacker News 首页(49 赞 / 29 评论,来源 belderbos.dev)。技术雷达每日自动聚合 AI 工程、后端架构、DevOps 方向的前沿动态;相关工程落地可浏览下方的相关服务与延伸阅读,或直接与我们团队交流。

原文来源: Hacker News

相关服务