Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Compiling Python to WebAssembly with py2wasm

Compiling Python to WebAssembly with py2wasm

Slides of the presentation for the Wasm I/O conference in March 15, 2024.

Syrus Akbary

March 16, 2024

More Decks by Syrus Akbary

Other Decks in Programming


  1. Can I compile Graphene to WebAssembly? WebAssembly could help on

    the quest of having an universal GraphQL library!
  2. Making Python go brr brr in Wasm • Use a

    Python subset that can be compiled into performant code • Use JIT inside of Python • Use Static Analysis to optimize code
  3. Python subset • Codon ➡ github.com/exaloop/codon • RPython ➡ rpython.readthedocs.io

    • Cython Optimize a smaller set ✅ Can be compiled to very performant code ❌ Doesn’t support the full syntax or modules JS Equivalent: Assemblyscript
  4. RPython Transforms the typed code into C, and then compiles

    it $ rpython hello_world.py hello-world-c.c
  5. Python JITs • Pypy ➡ pypy.org Compile the hot paths

    ✅ Really fast speeds ❌ Needs to warm up ❌ Not trivial to support with Wasm (but possible) JS Equivalent: V8, JasvascriptCore, SpiderMonkey
  6. PyPy JIT *Don’t miss Dmitry’s talk on JITs on Wasm

    with Spidermonkey 🔗 pypyjs.org
  7. But… it would take a bit more time to get

    right! JITs are possible, but not trivial -> More development time!
  8. Static Analysis • Mypy & Mypy-c ➡ mypy-lang.org • Nuitka

    ➡ github.com/Nuitka/Nuitka Performant code based on the types ✅ Mostly compatible with Python ❌ Only 1.5-3x faster ❌ Complex to get right ❌ Larger binaries JS Equivalent: Static Hermes, TypescriptCompiler
  9. Nuitka Python to CPython transpiler • It supports most Python

    programs. Transpiles Python code into the corresponding CPython calls • It can even work as a code obfuscator (no one will be able to decompile your program!)
  10. Will it compile to WASI? If Nuitka generates C code,

    and then uses a compiler… can we just switch the compiler?
  11. Not that simple! ❌ Not compatible with Python 3.12+ ❌

    Doesn’t support cross compiling to di ff erent architectures (64 to 32 bits)
  12. Plan Ahead • Compile Wasmer Django backend to Wasm via

    py2wasm • Use WASIX for full asyncio, threads and sockets support • py2wasm working fully inside of wasmer Future plans!