A Rust API Inspired by Python, Powered by Serde

https://news.ycombinator.com/rss Hits: 7
Summary

Years ago, I worked on reimplementing some Python code in Rust (yet again), and this time I needed to adapt Python’s dynamic capabilities (aka __getattr__) to the strict and compiled world of Rust.After some deliberation, and armed with the serde (de)serialization crate, I set out to do just that.So if you ever wondered what tricks Rust can learn from Python, and if serde can be used for reflection (please go along with me here), then the answer is very much yes!Let me show you how, and also why.Note: I’ll try to keep this somewhat approachable to Python programmers with only passing experience in Rust, it’ll be fun. 🦀🐍A Python InspirationUsing Python (on Windows), there’s a magical package that can be used to get all sorts of information about the system.Without going into too much detail, it boils down to this: Say you want to list all the installed physical fans. You can do that using the following code:import wmi c = wmi.WMI() for fan in c.Win32_Fan(): if fan.ActiveCooling: print(f"Fan `{fan.Name}` is running at {fan.DesiredSpeed} RPM") This uses a couple of clever __getattr__ implementations, and ends up running this equivalent code behind the scenes:for fan in c.query("SELECT * FROM Win32_Fan"): if fan.wmi_property("ActiveCooling").value is True: print(f"Fan `{fan.wmi_property('Name').value}` is running at {fan.wmi_property('DesiredSpeed').value} RPM") (The wmi_property method returns another object which holds the final value as well as its type.)Putting aside what WMI even is, this is the kind of thing Python is extraordinarily good at: A clear, concise, and intuitive interface abstracting over a complex and gnarly implementation.In Python, you need but override a few magic methods to implement this, but Rust is a completely different beast.What can we do if we want to create a Rust crate that provides a nice API to users, similar to the one above?What We Are Abstracting OverIt’ll help to start by expressing the “raw” API in pure Rust. It’s raw in the sense ...

First seen: 2025-05-15 14:39

Last seen: 2025-05-15 20:40