<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Will Pringle on Medium]]></title>
        <description><![CDATA[Stories by Will Pringle on Medium]]></description>
        <link>https://medium.com/@willkantorpringle?source=rss-ecb0726d6fe5------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*w5HuXCnzGeQK-yRzjKwggw.jpeg</url>
            <title>Stories by Will Pringle on Medium</title>
            <link>https://medium.com/@willkantorpringle?source=rss-ecb0726d6fe5------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 26 Nov 2026 10:20:08 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@willkantorpringle/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com" rel="hub"/>
        <item>
            <title><![CDATA[PythonMonkey: JavaScript/WASM Interop in Python using SpiderMonkey Bindings]]></title>
            <link>https://medium.com/@willkantorpringle/pythonmonkey-javascript-wasm-interop-in-python-using-spidermonkey-bindings-4a8efce2e598?source=rss-ecb0726d6fe5------2</link>
            <guid isPermaLink="false">https://medium.com/p/4a8efce2e598</guid>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[pythonmonkey]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[interoperability]]></category>
            <dc:creator><![CDATA[Will Pringle]]></dc:creator>
            <pubDate>Fri, 28 Jul 2023 21:56:52 GMT</pubDate>
            <atom:updated>2023-08-24T12:45:37.127Z</atom:updated>
            <content:encoded><![CDATA[<h3>Run JavaScript/WASM in Python: high-level SpiderMonkey bindings to Python with PythonMonkey</h3><p>Announcing PythonMonkey’s alpha release — use Python code in JavaScript and vice versa with ease and virtually no performance loss!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eiD8i14Cd6c0ooqoT29CcQ.png" /></figure><p>Play around with it on a Google Colab: <a href="https://colab.research.google.com/drive/1INshyn0gNMgULQVtXlQWK1QuDGwdgSGZ?usp=sharing">https://colab.research.google.com/drive/1INshyn0gNMgULQVtXlQWK1QuDGwdgSGZ?usp=sharing</a></p><p>Check out the documentation: <a href="https://docs.pythonmonkey.io/">https://docs.pythonmonkey.io/</a></p><h3>Introduction &amp; Goals</h3><p><a href="https://pythonmonkey.io/">PythonMonkey</a> (<a href="https://github.com/Distributive-Network/PythonMonkey/">GitHub Link</a>) is a Python library used for interoperation between Python and JavaScript built using Mozilla’s SpiderMonkey JavaScript engine. It will enable JavaScript libraries to be used seamlessly in Python code and vice versa — without any significant performance penalties. For instance, it’ll be possible to call Python packages like NumPy from within a JavaScript library, or use NPM packages like <a href="https://www.npmjs.com/package/crypto-js">crypto-js</a> directly from Python. Also, executing WebAssembly modules in Python becomes trivial using the WebAssembly API and engine from SpiderMonkey. Additionally, developers could use PythonMonkey to refactor a slow “hot loop” written in Python to execute in JS instead, taking advantage of SpiderMonkey’s just-in-time compiler for near-native speed.</p><p>PythonMonkey also ships with PMJS, a JavaScript runtime environment like Node.js that supports calling Python libraries from JavaScript.</p><h3>Here are a few simple code examples:</h3><p>Below is a ‘hello world’ example which demonstrates a string generated from JavaScript being returned to a Python context:</p><pre>&gt;&gt;&gt; import pythonmonkey as pm<br>&gt;&gt;&gt; hello = pm.eval(&quot; &#39;Hello World&#39;.toUpperCase(); &quot;)<br>&gt;&gt;&gt; print(hello)<br>&#39;HELLO WORLD&#39;</pre><p>This more involved example demonstrates passing the Python print function as an argument to a JavaScript function and then calling that JavaScript function from Python:</p><pre>&gt;&gt;&gt; import pythonmonkey as pm<br>&gt;&gt;&gt; hello = pm.eval(&quot;(func) =&gt; { func(&#39;Hello World!&#39;)}&quot;)<br>&gt;&gt;&gt; hello(print)<br>Hello World!</pre><p>This example uses pmjs to execute a JavaScript file that uses Python’s print function (This can be executed with pmjs main.js):<br><strong><em>main.js</em></strong></p><pre>const pyPrint = python.eval(&quot;print&quot;);<br>pyPrint(&quot;Hello, World!&quot;); // this outputs &quot;Hello, World!&quot;</pre><h3>Here are a few examples of PythonMonkey’s module system in use:</h3><p>PythonMonkey will allow developers to easily port their JavaScript libraries to Python, without suffering the costly burden of rewriting their libraries in Python and maintaining the ports. JavaScript is also ideal for highly asynchronous work loads, whereas Python is not. At <a href="https://distributive.network/">Distributive</a>, we intend to use this library to execute our complex <a href="https://docs.dcp.dev/api/dcp-client/index.html">dcp-client</a> library, which is written in JS, and enables distributed computing on the web stack.</p><p>Requiring a JavaScript file from Python:<br><strong><em>my-javascript-module.js</em></strong></p><pre>exports.sayHello = () =&gt; { console.log(&#39;hello, world&#39;) };</pre><p><strong><em>main.py</em></strong></p><pre>import pythonmonkey as pm<br>test = pm.require(&#39;./my-javascript-module&#39;);<br>test.sayHello() # this prints hello, world</pre><p>Loading a Python <a href="https://en.wikipedia.org/wiki/CommonJS">CommonJS</a> module from JavaScript:<br><strong><em>my-python-module.py</em></strong></p><pre>def getStringLength(s):<br>  return len(s)<br><br>exports[&#39;getStringLength&#39;] = getStringLength</pre><p><strong><em>my-javascript-module.js</em></strong></p><pre>const { getStringLength } = require(&#39;./my-python-module&#39;);<br><br>function printStringLength(s) {<br>  console.log(`String: &quot;${s}&quot; has a length of ${getStringLength(s)}`);<br>}<br><br>module.exports = { printStringLength, };</pre><p><strong><em>main.py</em></strong></p><pre>import pythonmonkey as pm<br>test = pm.require(&#39;./my-javascript-module&#39;);<br>test.printStringLength(&quot;Hello, world!&quot;) # String: &quot;Hello, world!&quot; has a length of 13</pre><h3>Calling WebAssembly function in Python:</h3><p>PythonMonkey also leverages other SpiderMonkey features such as its WebAssembly (WASM) engine which allows Python to run untrusted WASM code in a sandbox from a variety of languages such as C, C++, Rust, and others.</p><p>Check out the following YouTube tutorials on using WebAssembly in Python with PythonMonkey:</p><ul><li>Executing Rust from Python with WASM: <a href="https://youtu.be/jYCD0I-gdo8">https://youtu.be/jYCD0I-gdo8</a></li><li>Executing C from Python with WASM: <a href="https://youtu.be/xY39gePJhX8">https://youtu.be/xY39gePJhX8</a></li></ul><p>Calling a WebAssembly function in Python:</p><pre>import asyncio<br>import pythonmonkey as pm<br><br>async def async_fn():<br>  # read the factorial.wasm binary file<br>  file = open(&#39;factorial.wasm&#39;, &#39;rb&#39;)<br>  wasm_bytes = bytearray(file.read())<br><br>  # instantiate the WebAssembly code<br>  WebAssembly = pm.eval(&#39;WebAssembly&#39;)<br>  wasm_fact = await WebAssembly.instantiate(wasm_bytes, {})<br><br>  # return the &quot;fac&quot; factorial function from the wasm module<br>  return wasm_fact.instance.exports.fac;<br><br># await the promise which returns the factorial WebAssembly function<br>factorial = asyncio.run(async_fn())<br><br># execute WebAssembly code in Python!<br>print(factorial(4)) # this outputs &quot;24.0&quot; since factorial(4) == 24<br>print(factorial(5)) # this outputs &quot;120.0&quot;<br>print(factorial(6)) # this outputs &quot;720.0&quot;</pre><p>For more examples, check out our <a href="https://github.com/Distributive-Network/PythonMonkey-examples">examples repository on GitHub</a> and a repository for a <a href="https://github.com/Distributive-Network/PythonMonkey-Crypto-JS-Fullstack-Example">sample fullstack app that uses the CryptoJS NPM package in Python</a>.</p><h3>Implementation and Roadmap</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MSAtXVZd6T5AWrXVRRIPkQ.jpeg" /></figure><p>PythonMonkey is designed to share immutable backing stores whenever possible. This approach is vital to control memory consumption and eliminate memory-copy overhead when moving large strings between JS and Python. Other data types are managed using ‘proxy’ data structures that understand how to talk to the underlying data. For example, when a Python dictionary is passed to a JavaScript function, a ‘proxy’ object is created. This acts as an intermediary, enabling JavaScript to read from or write to the Python dictionary. Functions also operate similarly with a proxy wrapper. Intrinsics like Boolean, Number, null, undefined are passed by value.</p><p>PythonMonkey’s roadmap includes a number of features and improvements to expand its usability, such as importing Python modules in JavaScript using esm syntax, XMLHttpRequest, implementing a standalone event loop without relying on Python’s, and support for Node.js APIs such as fs, path, process, which would allow Python to use NPM packages like <a href="https://expressjs.com/">express.js</a> and <a href="https://socket.io/">socket.io</a>. Another proposed goal further down the roadmap is to expand PMJS into a a fully integrated Node.js environment which could act as a drop-in replacement for Node.js that also has the ability to use Python packages from JavaScript.</p><p>With these planned enhancements, PythonMonkey and PMJS aim to offer a fully integrated Python-JS environment for developers. We are looking for contributors to PythonMonkey to help add these features; if you’re interested, please check out the project’s <a href="https://github.com/Distributive-Network/PythonMonkey">GitHub page</a>.</p><h4>A Future Challenge</h4><p>A new Python proposal, <a href="https://peps.python.org/pep-0623/">PEP 623</a>, plans to remove legacy strings, a necessary feature PythonMonkey depends on to efficiently pass string data back and forth. Legacy strings allow for a data buffer from anywhere; hence, it can point directly to a JSString’s buffer. Without them, PythonMonkey will need to make a copy of the JSString’s buffer, leading to significant time and memory inefficiencies.</p><h3>Related Projects</h3><p>Several projects exist already for running JavaScript within Python, such as <a href="https://github.com/PiotrDabkowski/Js2Py">JS2PY</a>, <a href="https://code.google.com/archive/p/pyv8/">PyV8</a>, and <a href="https://github.com/metacall/core">Metacall</a>.</p><p>JS2Py is implemented entirely in Python, a characteristic that might seem attractive as it eliminates the need for substantial engines like V8 or SpiderMonkey. However, this approach brings its own set of challenges. Not utilizing an existing JavaScript engine denies JS2Py the opportunity to benefit from robust, continuously updated, and proven codebases that engines like V8 or SpiderMonkey offer in browsers used by millions of people every day. Furthermore, JS2Py misses out on functionalities such as a WASM engine, support for the latest JavaScript specification (ECMA-262), and a powerful JIT, which come built-in with these engines. JavaScript Promises and Async/Await, which are used extensively in modern asynchronous JS programming, are also missing in JS2Py but are available in PythonMonkey. Finally, being written in Python, JS2Py faces performance constraints that aren’t present in SpiderMonkey; the <a href="https://en.wikipedia.org/wiki/Browser_speed_test#SunSpider_(superseded)">SunSpider JavaScript benchmark</a> reports a 1162.5× speedup from using PythonMonkey over JS2Py.</p><p>PyV8, <a href="https://github.com/cloudflare/stpyv8">and Cloudflare’s modern implementation of it</a>, are Python wrappers for Google’s V8 JavaScript engine bindings. This means it operates at a lower level than PythonMonkey and <a href="https://github.com/cloudflare/stpyv8/issues/46">doesn’t support event loop functionality such as JavaScript’s promises and async/await</a>.</p><p>Metacall is an extensible, embeddable and interoperable cross-platform polyglot runtime that interoperates with a number of programming languages such as JavaScript, Python, Ruby, Rust, C#, Java and more. This means Metacall can be used to interoperate between Python and JavaScript similarly to PythonMonkey. However, the extensive supported languages Metacall supports comes at a cost, and requires additional software to be installed on a system beyond a Python package for it to operate. Additionally, Metacall makes copies of data it passes between Python and JavaScript instead of passing by reference like how PythonMonkey does leading to performance impacts.</p><p>While alternative projects have similarities with PythonMonkey’s model, they fall short of PythonMonkey’s proposed interoperability, ease of use, and speed.</p><h3>Try it out</h3><p>Play around with it on a Google Collab: <a href="https://colab.research.google.com/drive/1INshyn0gNMgULQVtXlQWK1QuDGwdgSGZ?usp=sharing">https://colab.research.google.com/drive/1INshyn0gNMgULQVtXlQWK1QuDGwdgSGZ?usp=sharing</a></p><p>If you’re interested in trying out PythonMonkey or PMJS on your system, you can either install via pip:<br>$ pip install pythonmonkey <br>or follow the build instructions on our <a href="https://github.com/Distributive-Network/PythonMonkey">GitHub page: https://github.com/Distributive-Network/PythonMonkey</a>. Note: PythonMonkey requires npm to be installed on a system during its build process.</p><h3>Stay tuned for more PythonMonkey blog posts</h3><p>We’ll continue to make more blog posts as we implement features in PythonMonkey. If you’re interested in learning more and staying up to date, <a href="https://forms.gle/DsmMJ49nadLzgVhC8">subscribe to our newsletter for updates</a>, join our discord <a href="https://discord.gg/8KvEGZas9R">https://discord.gg/8KvEGZas9R</a>, and check out the project’s website: <a href="https://pythonmonkey.io/">https://pythonmonkey.io/</a></p><p>If you’re interested in contributing to PythonMonkey, check out the project on GitHub: <a href="https://github.com/Distributive-Network/PythonMonkey">https://github.com/Distributive-Network/PythonMonkey</a></p><p>And feel free to get in touch with the PythonMonkey team!<br>pm@distributive.network</p><p><strong>NOTE — I did not create PythonMonkey!</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*rQmXTHy0tYsdOckxGBNQKQ.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4a8efce2e598" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Calling C functions in Python using WebAssembly]]></title>
            <link>https://medium.com/@willkantorpringle/calling-c-function-from-python-using-webassembly-63a305248951?source=rss-ecb0726d6fe5------2</link>
            <guid isPermaLink="false">https://medium.com/p/63a305248951</guid>
            <category><![CDATA[webassembly]]></category>
            <category><![CDATA[pythonmonkey]]></category>
            <category><![CDATA[emscripten]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[c]]></category>
            <dc:creator><![CDATA[Will Pringle]]></dc:creator>
            <pubDate>Tue, 25 Jul 2023 14:47:11 GMT</pubDate>
            <atom:updated>2023-08-24T12:47:07.528Z</atom:updated>
            <cc:license>http://creativecommons.org/publicdomain/zero/1.0/</cc:license>
            <content:encoded><![CDATA[<p>Using PythonMonkey and Emscripten to call C code from Python!</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fround-lake.dustinice.workers.dev%3A443%2Fhttps%2Fwww.youtube.com%2Fembed%2FxY39gePJhX8%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fround-lake.dustinice.workers.dev%3A443%2Fhttps%2Fwww.youtube.com%2Fwatch%3Fv%3DxY39gePJhX8&amp;image=https%3A%2F%2Fround-lake.dustinice.workers.dev%3A443%2Fhttps%2Fi.ytimg.com%2Fvi%2FxY39gePJhX8%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/ed1a682c1fba11d66848397fa77c8d92/href">https://medium.com/media/ed1a682c1fba11d66848397fa77c8d92/href</a></iframe><p>This article will cover how to use <a href="https://pythonmonkey.io">PythonMonkey</a> and <a href="https://emscripten.org/index.html">Emscripten</a> to compile a C library to WebAssembly and use it in Python. Emscripten is a tool for compiling C code to WebAssembly(WASM). PythonMonkey on the other hand is a Python library for executing JavaScript and WASM in Python. Using both of these tools creates a powerful workflow for executing C in Python with the added benefits of WebAssembly.</p><p>All the code from this article is available on <a href="https://github.com/wiwichips/pythonmonkey-emscripten-example">GitHub</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RAetQiwiK_QQN8LtZKbPOg.png" /><figcaption>Emscripten compiles C to WebAssembly &amp; PythonMonkey runs WebAssembly in Python.</figcaption></figure><h3>Required Software Installation</h3><p>You’ll need to install Emscripten and PythonMonkey if you haven’t already.</p><h4>Install Emscripten</h4><p>Follow the installation instructions here: <a href="https://emscripten.org/docs/getting_started/downloads.html">https://emscripten.org/docs/getting_started/downloads.html</a></p><h4>Install PythonMonkey</h4><p>PythonMonkey requires Python3.8 or higher. It can be installed using pip:</p><pre>pip install pythonmonkey</pre><h3>Writing a C Library</h3><p>We’ll write a basic C library called my_c_lib.c with two simple functions for addition and subtraction:</p><pre>int add(int a, int b) {<br>	return a + b;<br>}<br><br>int sub(int a, int b) {<br>	return a - b;<br>}</pre><p>However, for us to export these functions as part of the API when the library gets compiled to WebAssembly, we’ll need to use a couple macros from the Emscripten C library.</p><pre>#include &lt;emscripten.h&gt;<br><br>EMSCRIPTEN_KEEPALIVE<br>int add(int a, int b) {<br>	return a + b;<br>}<br><br>EMSCRIPTEN_KEEPALIVE<br>int sub(int a, int b) {<br>	return a - b;<br>}</pre><p>The EMSCRIPTEN_KEEPALIVE macro is used to ensure the function is exported and not eliminated as dead code by the compiler. For more information, refer to the <a href="https://emscripten.org/docs/api_reference/emscripten.h.html#c.EMSCRIPTEN_KEEPALIVE">Emscripten API</a>.</p><h3>Compiling C to WebAssembly .wasm Code</h3><p>Next, we’ll use Emscripten’s emcc tool to compile our C library to WASM by running the following command:</p><pre>emcc my_c_lib.c -s WASM=1 -s SIDE_MODULE=1 -o my_c_lib.wasm</pre><p>Running this command will create a new file my_c_lib.wasm.</p><h3>Calling the C Library from Python with PythonMonkey</h3><p>We’ll use <a href="https://pythonmonkey.io/">PythonMonkey</a> to load and make calls to the WebAssembly generated C library. PythonMonkey is a Python library powered by <a href="https://spidermonkey.dev/">Mozilla’s SpiderMonkey JS engine</a> for executing JavaScript, or WebAssembly, in Python.</p><p>Here’s a simple Python script that calls the C library functions we wrote using PythonMonkey:</p><pre>import pythonmonkey as pm<br><br># get the WebAssembly module from JS<br>WebAssembly = pm.eval(&#39;WebAssembly&#39;)<br><br># read the wasm file<br>file = open(&#39;my_c_lib.wasm&#39;, &#39;rb&#39;)<br>wasm_bytes = bytearray(file.read())<br><br># instantiate a new wasm module<br>wasm_module = pm.new(WebAssembly.Module)(wasm_bytes)<br><br># create an import object which specifies the wasm environment<br>import_object = {<br>    &#39;env&#39;: {<br>        &#39;__memory_base&#39;: 0,<br>        &#39;__table_base&#39;: 0,<br>        &#39;memory&#39;: pm.eval(&#39;new WebAssembly.Memory({ initial: 256, maximum: 256 })&#39;),<br>        &#39;table&#39;: pm.eval(&#39;new WebAssembly.Table({ initial: 0, maximum: 0, element: &quot;anyfunc&quot; })&#39;),<br>        &#39;__indirect_function_table&#39;: pm.eval(&#39;new WebAssembly.Table({ initial: 0, maximum: 0, element: &quot;anyfunc&quot; })&#39;),<br>        &#39;__stack_pointer&#39;: pm.eval(&#39;new WebAssembly.Global({ value: &quot;i32&quot;, mutable: true }, 8192)&#39;),<br>        &#39;abort&#39;: lambda: exec(&#39;raise Exception(&quot;Abort!&quot;)&#39;) <br>    }<br>}<br><br># call the add function from the library<br>my_c_lib = pm.new(WebAssembly.Instance)(wasm_module, import_object).exports;<br>print(my_c_lib.add(1,2)) #  3.0<br>print(my_c_lib.sub(1,2)) # -1.0</pre><ul><li>WebAssembly = pm.eval(&#39;WebAssembly&#39;) grabs the WebAssembly global module from JavaScript and assigns it to a variable called WebAssembly in python.</li><li>wasm_module = pm.new(WebAssembly.Module)(wasm_bytes) instantiates a new WebAssembly module using the WebAssembly. Module class and passes wasm_bytes, a bytearray containing the bytes of the c library we compiled to WASM, to the constructor. We use pm.new to instantiate it because Python lacks a new keyword and JavaScript class constructors require new to instantiate properly. Note: thepm.new API was added in PythonMonkey version 0.2.1.</li><li>import_object specifies the environment for out WebAssembly to execute in such as its memory. We’ll also pass a function to be executed on abort.</li><li>my_c_lib = pm.new(WebAssembly.Instance)(wasm_module, import_object).exports assigns my_c_lib to an Object that contains all the functions from our C library</li><li>Then, to execute any of the functions, we can just do my_c_lib.add(1,2) or my_c_lib.sub(1,2)</li></ul><p>We can execute this script my typing python3 script.py (replace “script.py” with whatever you called it).</p><h3>Conclusion</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PNx5YrI2zTZMAPkjcE0yQw.png" /><figcaption>Pretty picture that doesn’t really explain that much.</figcaption></figure><p>In conclusion, we used PythonMonkey and Emscripten to execute C functions in Python really easily. PythonMonkey can do much more than execute WebAssembly. You can use it to load NPM packages in Python, improve Python’s speed using SpiderMonkey’s JIT, and more. Consider checking the project out on GitHub and giving it a star: <a href="https://github.com/Distributive-Network/PythonMonkey">https://github.com/Distributive-Network/PythonMonkey</a></p><p>Check out PythonMonkey’s documentation for more information: <a href="https://docs.pythonmonkey.io/">https://docs.pythonmonkey.io/</a></p><p>Also, if you’re interested in another article calling Rust from Python using a similar method, check out my other article: <a href="https://medium.com/@willkantorpringle/executing-rust-in-python-using-webassembly-d361eb5583da">https://medium.com/@willkantorpringle/executing-rust-in-python-using-webassembly-d361eb5583da</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=63a305248951" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Executing Rust in Python using WebAssembly ]]></title>
            <link>https://medium.com/@willkantorpringle/executing-rust-in-python-using-webassembly-d361eb5583da?source=rss-ecb0726d6fe5------2</link>
            <guid isPermaLink="false">https://medium.com/p/d361eb5583da</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[rust]]></category>
            <category><![CDATA[pythonmonkey]]></category>
            <category><![CDATA[webassembly]]></category>
            <dc:creator><![CDATA[Will Pringle]]></dc:creator>
            <pubDate>Sun, 23 Jul 2023 15:59:31 GMT</pubDate>
            <atom:updated>2023-08-24T12:46:34.602Z</atom:updated>
            <cc:license>http://creativecommons.org/publicdomain/zero/1.0/</cc:license>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/760/1*RkURwedB4zI7XX9HOCSChw.jpeg" /><figcaption><a href="https://digitalcollections.nypl.org/items/510d47e2-326e-a3d9-e040-e00a18064a99"><em>The snake and the crab</em></a></figcaption></figure><p>Using PythonMonkey and wasm-bindgen to call Rust from Python!</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fround-lake.dustinice.workers.dev%3A443%2Fhttps%2Fwww.youtube.com%2Fembed%2FjYCD0I-gdo8%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fround-lake.dustinice.workers.dev%3A443%2Fhttps%2Fwww.youtube.com%2Fwatch%3Fv%3DjYCD0I-gdo8&amp;image=https%3A%2F%2Fround-lake.dustinice.workers.dev%3A443%2Fhttps%2Fi.ytimg.com%2Fvi%2FjYCD0I-gdo8%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/3f0066954aacc286c935c2767f8113e7/href">https://medium.com/media/3f0066954aacc286c935c2767f8113e7/href</a></iframe><h3>Introduction</h3><p>This tutorial will go over using <a href="https://rustwasm.github.io/wasm-bindgen/">wasm-bindgen</a> and <a href="https://pythonmonkey.io/">PythonMonkey</a> to compile and execute rust code from Python. <a href="https://rustwasm.github.io/wasm-bindgen/">Wasm-bindgen</a> is a Rust library that makes it easier to call Rust WASM code from JavaScript and vice versa. <a href="https://pythonmonkey.io/">PythonMonkey</a> is a Python library for running JavaScript and WebAssembly in Python. Using PythonMonkey and wasm-bindgen, we can easily call Rust code from Python in a secure and portable WebAssembly sandbox.</p><p>This tutorial is based on an MDN article titled <a href="https://developer.mozilla.org/en-US/docs/WebAssembly/Rust_to_Wasm">Compiling from Rust to WebAssembly</a>.</p><p>All the code from article will be available on <a href="https://github.com/Distributive-Network/pythonmonkey-rust-wasm-example">GitHub</a></p><h3>Required Software Installation</h3><h4>Install Rust, and Cargo:</h4><p>Rust uses Cargo for package management. Follow the instructions here: <a href="https://doc.rust-lang.org/cargo/getting-started/installation.html">https://doc.rust-lang.org/cargo/getting-started/installation.html</a></p><h4>Install Python and pip</h4><p>Install Python with a minimum version of 3.8.</p><h4>Install PythonMonkey</h4><p><strong>PythonMonkey</strong> is required to run WebAssembly from Python.</p><pre>pip install pythonmonkey</pre><h4>Install wasm-pack</h4><p><strong>wasm-pack</strong> is a command line tool for compiling rust code to WASM and providing a JavaScript package as an API for the code.</p><pre>cargo install wasm-pack</pre><h3>Building a Rust WebAssembly Package</h3><p>First, use cargo to generate a new library for us to get started in.</p><pre>cargo new --lib my-rust-library</pre><p>This creates a new library in a sub-directory named <strong>my-rust-library</strong> with everything you need to get going:</p><pre>├── Cargo.toml<br>└── src<br>    └── lib.rs</pre><p>First, we have <strong>Cargo.toml</strong>; this is the file that we use to configure our build. If you’ve used Gemfile from Bundler or <strong>package.json</strong> from <strong>npm</strong>, this is likely to be familiar; Cargo works in a similar manner to both of them.</p><p>Next, Cargo has generated some Rust code for us in <strong>src/lib.rs</strong>:</p><pre>#[cfg(test)]<br>mod tests {<br>    #[test]<br>    fn it_works() {<br>        assert_eq!(2 + 2, 4);<br>    }<br>}</pre><p>We won’t use this test code at all, so go ahead and delete it.</p><h3>Writing a Rust Library for our Python to Call</h3><p>Let’s put this code into <strong>src/lib.rs</strong> instead:</p><pre>use wasm_bindgen::prelude::*;<br><br>#[wasm_bindgen]<br>pub fn add(a: u32, b: u32) -&gt; u32{<br>  a + b<br>}</pre><p><strong>add</strong> is a simple function that returns the sum of two numbers. More complicated functions can be used, but let’s start with a simple example for now.</p><h3>Compiling our code to WebAssembly</h3><p>To compile our code correctly, we first need to configure it with <strong>Cargo.toml</strong>. Open this file, and change its contents to look like this:</p><pre>[package]<br>name = &quot;hello-wasm&quot;<br>version = &quot;0.1.0&quot;<br>edition = &quot;2021&quot;<br><br>[lib]<br>crate-type = [&quot;cdylib&quot;]<br><br>[dependencies]<br>wasm-bindgen = { version = &quot;0.2.84&quot; }</pre><h3>Building the package</h3><p>Now that we’ve got everything set up, let’s build the package. Type this into your terminal:</p><pre>wasm-pack build --target nodejs</pre><p>This command performs a number of actions:</p><ul><li>Compiles our Rust code to WebAssembly.</li><li>Runs wasm-bindgen on that WebAssembly, generating a JavaScript file that wraps up that WebAssembly file into a module that can be loaded from JavaScript.</li><li>Creates a <strong>pkg</strong> directory and moves that JavaScript file and your WebAssembly code into it.</li></ul><p>The main outcome is that we now have a JavaScript package in the <strong>pkg/</strong> directory</p><h3>An Extra Build Step</h3><p>Currently, PythonMonkey has limited support for Node.js libraries, so we’ll need to add an extra step to the build process to convert the calls to Node.js libraries with PythonMonkey friendly ones.</p><p>The call to wasm-pack outputs code using <strong>readFileSync</strong> from Node.js’ <strong>fs</strong> library and <strong>join</strong> from its <strong>path</strong> library. We’ll need to replace these with the following:</p><pre>function readFileSync(filename) {<br>  python.exec(`<br>def getBytes(filename):<br>  with open(filename, &#39;rb&#39;) as f:<br>    return bytearray(f.read())<br>  `);<br>  return python.eval(&#39;getBytes&#39;)(filename)<br>}</pre><pre>[a,b].join(&#39;/&#39;) # require(&#39;path&#39;).join(a,b)</pre><p>To simplify and automate this process, I’ll include these in a shell script called <strong>build.sh</strong> that runs <strong>wasm-pack</strong> and injects these function definitions using sed.</p><p>Place <strong>build.sh</strong> in the same directory as your <strong>Cargo.toml</strong> and paste in the following code:</p><pre>#!/usr/bin/env bash<br>#<br># This shell script compiles the rust library to WebAssembly and creates a JS package using wasm-pack. <br># It also replaces any Node.js specific code with PythonMonkey code using sed.<br>#<br># Note: this script is only compatible with unix.<br>#<br><br># compiles rust code to wasm and creates a package targetting Node.js<br>wasm-pack build --target nodejs<br><br># replaces calls to require(&#39;path&#39;) and require(&#39;fs&#39;) with pythonmonkey non Node.js equivalents<br>NEW_READ_FILE_SYNC=&quot;function pyReadFileSync(filename) {\n  python.exec(\n\\\`\ndef getBytes(filename):\n  file = open(filename, &#39;rb&#39;)\n  return bytearray(file.read())\n\\\`\n  );\n  return python.eval(&#39;getBytes&#39;)(filename)\n}\n&quot;<br><br>find ./pkg/*js -type f -exec sed -i &quot;s/require(&#39;path&#39;).join(\(.*\));/[\1]\.join(&#39;\/&#39;);/g&quot; {} \;<br>find ./pkg/*js -type f -exec sed -i &quot;s/require(&#39;fs&#39;).readFileSync(\(.*\));/(${NEW_READ_FILE_SYNC})(\1)/g&quot; {} \;</pre><p>Now, all we have to do is run <strong>./build.sh</strong> and it will compile our Rust to WASM and replace Node.js specific code with Python and vanilla JS equivalents.</p><h3>Executing the Rust code from Python</h3><p>Run your new <strong>build.sh</strong> script to compile your Rust code and get started with calling WASM code from Python!</p><pre>bash ./buils.sh</pre><p>Here is a simple python script that calls our add function:</p><pre>import pythonmonkey as pm<br><br>test = pm.require(&quot;./pkg/hello_wasm&quot;);<br><br>print(test.add(1,2))</pre><p>Run this script with python3 main.py and it will call our add function defined in rust and output 3.0 !</p><h3>Conclusion</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4mQ7kP-Zjf7gi4bVmTg6pA.png" /><figcaption>Calling Rust code compiled to WASM in Python using PythonMonkey</figcaption></figure><p>Well we wrote rust, compiled it to WASM and ran it in Python!</p><p>Although this example is very simple, it can be expanded on to run more complicated Rust code from Python. One use case could be a Python library that uses Rust for extra efficiency for complex operations.</p><p>Check out more about PythonMonkey here: <a href="https://pythonmonkey.io">https://pythonmonkey.io</a> and consider giving it a star on GitHub if you like the project <a href="https://github.com/Distributive-Network/PythonMonkey/">https://github.com/Distributive-Network/PythonMonkey/</a> 🐍🐵.</p><p>Refer to PythonMonkey’s documentation for more information: <a href="https://docs.pythonmonkey.io/">https://docs.pythonmonkey.io/</a> .</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d361eb5583da" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>