npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

use-pyodide

v0.1.3

Published

React hook to run pyodide in a web worker

Downloads

9

Readme

use-pyodide

A simple React hook to run Python code (using pyodide) in a web worker.

Install

npm install use-pyodide

If you're using NextJS, modify your next.config.js file to enable transpiling from Typescript:

/** @type {import('next').NextConfig} */
const nextConfig = {
  transpilePackages: ["use-pyodide"]
}

(If you'd prefer building some other way, let me know.)

usePyodide

To initialize pyodide and use it in a React component, just call the usePyodide hook:

import { usePyodide } from "use-pyodide";

const MyComponent = () => {
    const { pyodide, loading, error } = usePyodide();

    useEffect(() => {
        if (pyodide) {
            pyodide.runPython(`print("👋 from Python")`)
        }
    }, [pyodide]);

    ...
}

The first time usePyodide is called, it will download the Pyodide wasm bundle from JsDelivr and create a web worker to run it.

Multiple calls are fine, only one singleton instance will be created.

Preloading

Loading pyodide can take several seconds, so you may want to initialize it when your app first loads, before it's actually needed in components.

You can optionally do that by calling initializePyodide, like this:

import { initializePyodide } from "use-pyodide";

const MyApp = () => {
    useEffect(() => {
        initializePyodide({ debug: true });
    }, []);
}

Debug logging

If you call initializePyodide with debug: true, debug messages from stdout/stderr and elapsed times will be logged to the browser console, which can be useful during development.

Loading packages

By default, only the Python standard library is loaded.

To load other packages, just pass an array of package names to initializePyodide.

initializePyodide({
    packages: ["numpy", "pandas"]
})

Many packages have been built for pyodide: https://pyodide.org/en/stable/usage/packages-in-pyodide.html

In addition to these, pure Python packages typically work.

Packages are installed using micropip.install, as described here.

Executing python

Once you have a pyodide object, you can use it to execute Python code in your browser!

You can optionally pass in global vars to the Python execution namespace.

const pythonCode = "...";

const result = await pyodide.runPython(pythonCode, {
    args: {
        name: "Guido"
    }
});

You can access these global vars in Python like this:

import json

args = args or {}
name = args.get("name")

json.dumps({
    "message": f"Hi, {name}"
})

Using JSON

As a convenience, if your Python script returns a JSON string as its last expression, you can use runPythonJson to automatically JSON.parse the result:

const jsonObject = await pyodide.runPythonJson(code, globals);

Runs in a web worker

To avoid blocking the main UI thread, we run pyodide in a background web worker (using comlink), as described here:

https://pyodide.org/en/stable/usage/webworker.html

Accessing outside React

If needed, you can access pyodide outside of React components like this:

import { getPyodide } from "use-pyodide";

const pyodide: Pyodide = await getPyodide();

License

MIT license.

Feel free to copy/fork code as you like. No need for attribution, but if you find this library helpful or build something cool with it, let me know!