diff --git a/2024.9.1/search/search_index.json b/2024.9.1/search/search_index.json index 8cc00f0..7a699d9 100644 --- a/2024.9.1/search/search_index.json +++ b/2024.9.1/search/search_index.json @@ -1 +1 @@ -{"config":{"lang":["en"],"separator":"[\\s\\-]+","pipeline":["stopWordFilter"]},"docs":[{"location":"","title":"Home","text":"PyScript is an open source platform for Python in the browser."},{"location":"#pyscript-is","title":"PyScript is...","text":"
Welcome, friend! PyScript is an open source project, we expect participants to act in the spirit of our code of conduct and we have many ways in which you can contribute. Our developer guide explains how to set up a working development environment for PyScript.
Just show me... That's easy! Just take a look around pyscript.com - our platform for developing and hosting PyScript applications. By using using this service you help to support and sustain the development and growth of the open-source PyScript project. I want support...Join the conversation on our discord server, for realtime chat with core maintainers and fellow users of PyScript. Check out our YouTube channel, full of community calls and show and tells. Explore educational and commercial support provided by our open source sponsor Anaconda Inc (this helps pay for and sustain PyScript!).
"},{"location":"api/","title":"Built-in APIs","text":"PyScript makes available convenience objects, functions and attributes.
In Python this is done via the builtin pyscript
module:
from pyscript import document\n
In HTML this is done via py-*
and mpy-*
attributes (depending on the interpreter you're using):
<button id=\"foo\" py-click=\"handler_defined_in_python\">Click me</button>\n
These APIs will work with both Pyodide and Micropython in exactly the same way.
Info
Both Pyodide and MicroPython provide access to two further lower-level APIs:
globalThis
via importing the js
module: import js
(now js
is a proxy for globalThis
in which all native JavaScript based browser APIs are found).PyScript can run in two contexts: the main browser thread, or on a web worker. The following three categories of API functionality explain features that are common for both main thread and worker, main thread only, and worker only. Most features work in both contexts in exactly the same manner, but please be aware that some are specific to either the main thread or a worker context.
"},{"location":"api/#common-features","title":"Common features","text":"These Python objects / functions are available in both the main thread and in code running on a web worker:
"},{"location":"api/#pyscriptconfig","title":"pyscript.config
","text":"A Python dictionary representing the configuration for the interpreter.
Reading the current configuration.from pyscript import config\n# It's just a dict.\nprint(config.get(\"files\"))\n
Warning
Changing the config
dictionary at runtime has no effect on the actual configuration.
It's just a convenience to read the configuration at run time.
"},{"location":"api/#pyscriptcurrent_target","title":"pyscript.current_target
","text":"A utility function to retrieve the unique identifier of the element used to display content. If the element is not a <script>
and it already has an id
, that id
will be returned.
<!-- current_target(): explicit-id -->\n<mpy-script id=\"explicit-id\">\n from pyscript import display, current_target\n display(f\"current_target(): {current_target()}\")\n</mpy-script>\n<!-- current_target(): mpy-0 -->\n<mpy-script>\n from pyscript import display, current_target\n display(f\"current_target(): {current_target()}\")\n</mpy-script>\n<!-- current_target(): mpy-1 -->\n<!-- creates right after the <script>:\n <script-py id=\"mpy-1\">\n <div>current_target(): mpy-1</div>\n </script-py>\n-->\n<script type=\"mpy\">\nfrom pyscript import display, current_target\ndisplay(f\"current_target(): {current_target()}\")\n</script>\n
Note
The return value of current_target()
always references a visible element on the page, not at the current <script>
that is executing the code.
To reference the <script>
element executing the code, assign it an id
:
<script type=\"mpy\" id=\"unique-id\">...</script>\n
Then use the standard document.getElementById(script_id)
function to return a reference to it in your code.
pyscript.display
","text":"A function used to display content. The function is intelligent enough to introspect the object[s] it is passed and work out how to correctly display the object[s] in the web page based on the following mime types:
text/plain
to show the content as texttext/html
to show the content as HTMLimage/png
to show the content as <img>
image/jpeg
to show the content as <img>
image/svg+xml
to show the content as <svg>
application/json
to show the content as JSONapplication/javascript
to put the content in <script>
(discouraged)The display
function takes a list of *values
as its first argument, and has two optional named arguments:
target=None
- the DOM element into which the content should be placed. If not specified, the target
will use the current_script()
returned id and populate the related dedicated node to show the content.append=True
- a flag to indicate if the output is going to be appended to the target
.There are some caveats:
display
function automatically uses the current <py-script>
or <mpy-script>
tag as the target
into which the content will be displayed.<script>
tag has the target
attribute, and is not a worker, the element on the page with that ID (or which matches that selector) will be used to display the content instead.display
function needs an explicit target=\"dom-id\"
argument to identify where the content will be displayed.append=True
is the default behaviour.<!-- will produce\n <py-script>PyScript</py-script>\n-->\n<py-script worker>\n from pyscript import display\n display(\"PyScript\", append=False)\n</py-script>\n<!-- will produce\n <script type=\"py\">...</script>\n <script-py>PyScript</script-py>\n-->\n<script type=\"py\">\nfrom pyscript import display\ndisplay(\"PyScript\", append=False)\n</script>\n<!-- will populate <h1>PyScript</h1> -->\n<script type=\"py\" target=\"my-h1\">\nfrom pyscript import display\ndisplay(\"PyScript\", append=False)\n</script>\n<h1 id=\"my-h1\"></h1>\n<!-- will populate <h2>PyScript</h2> -->\n<script type=\"py\" worker>\nfrom pyscript import display\ndisplay(\"PyScript\", target=\"my-h2\", append=False)\n</script>\n<h2 id=\"my-h2\"></h2>\n
"},{"location":"api/#pyscriptdocument","title":"pyscript.document
","text":"On both main and worker threads, this object is a proxy for the web page's document object. The document
is a representation of the DOM and can be used to read or manipulate the content of the web page.
pyscript.fetch
","text":"A common task is to fetch
data from the web via HTTP requests. The pyscript.fetch
function provides a uniform way to achieve this in both Pyodide and MicroPython. It is closely modelled on the Fetch API found in browsers with some important Pythonic differences.
The simple use case is to pass in a URL and await
the response. If this request is in a function, that function should also be defined as async
.
from pyscript import fetch\nresponse = await fetch(\"https://example.com\")\nif response.ok:\ndata = await response.text()\nelse:\nprint(response.status)\n
The object returned from an await fetch
call will have attributes that correspond to the JavaScript response object. This is useful for getting response codes, headers and other metadata before processing the response's data.
Alternatively, rather than using a double await
(one to get the response, the other to grab the data), it's possible to chain the calls into a single await
like this:
from pyscript import fetch\ndata = await fetch(\"https://example.com\").text()\n
The following awaitable methods are available to you to access the data returned from the server:
arrayBuffer()
returns a Python memoryview of the response. This is equivalent to the arrayBuffer()
method in the browser based fetch
API.blob()
returns a JavaScript blob
version of the response. This is equivalent to the blob()
method in the browser based fetch
API.bytearray()
returns a Python bytearray
version of the response.json()
returns a Python datastructure representing a JSON serialised payload in the response.text()
returns a Python string version of the response.The underlying browser fetch
API has many request options that you should simply pass in as keyword arguments like this:
from pyscript import fetch\nresult = await fetch(\"https://example.com\", method=\"POST\", body=\"HELLO\").text()\n
Danger
You may encounter CORS errors (especially with reference to a missing Access-Control-Allow-Origin header.
This is a security feature of modern browsers where the site to which you are making a request will not process a request from a site hosted at another domain.
For example, if your PyScript app is hosted under example.com
and you make a request to bbc.co.uk
(who don't allow requests from other domains) then you'll encounter this sort of CORS related error.
There is nothing PyScript can do about this problem (it's a feature, not a bug). However, you could use a pass-through proxy service to get around this limitation (i.e. the proxy service makes the call on your behalf).
"},{"location":"api/#pyscriptffi","title":"pyscript.ffi
","text":"The pyscript.ffi
namespace contains foreign function interface (FFI) methods that work in both Pyodide and MicroPython.
pyscript.ffi.create_proxy
","text":"A utility function explicitly for when a callback function is added via an event listener. It ensures the function still exists beyond the assignment of the function to an event. Should you not create_proxy
around the callback function, it will be immediately garbage collected after being bound to the event.
Warning
There is some technical complexity to this situation, and we have attempted to create a mechanism where create_proxy
is never needed.
Pyodide expects the created proxy to be explicitly destroyed when it's not needed / used anymore. However, the underlying proxy.destroy()
method has not been implemented in MicroPython (yet).
To simplify this situation and automatically destroy proxies based on JavaScript memory management (garbage collection) heuristics, we have introduced an experimental flag:
experimental_create_proxy = \"auto\"\n
This flag ensures the proxy creation and destruction process is managed for you. When using this flag you should never need to explicitly call create_proxy
.
The technical details of how this works are described here.
"},{"location":"api/#pyscriptffito_js","title":"pyscript.ffi.to_js
","text":"A utility function to convert Python references into their JavaScript equivalents. For example, a Python dictionary is converted into a JavaScript object literal (rather than a JavaScript Map
), unless a dict_converter
is explicitly specified and the runtime is Pyodide.
The technical details of how this works are described here.
"},{"location":"api/#pyscriptjs_modules","title":"pyscript.js_modules
","text":"It is possible to define JavaScript modules to use within your Python code.
Such named modules will always then be available under the pyscript.js_modules
namespace.
Warning
Please see the documentation (linked above) about restrictions and gotchas when configuring how JavaScript modules are made available to PyScript.
"},{"location":"api/#pyscriptstorage","title":"pyscript.storage
","text":"The pyscript.storage
API wraps the browser's built-in IndexDB persistent storage in a synchronous Pythonic API.
Info
The storage API is persistent per user tab, page, or domain, in the same way IndexedDB persists.
This API is not saving files in the interpreter's virtual file system nor onto the user's hard drive.
from pyscript import storage\n# Each store must have a meaningful name.\nstore = await storage(\"my-storage-name\")\n# store is a dictionary and can now be used as such.\n
The returned dictionary automatically loads the current state of the referenced IndexDB. All changes are automatically queued in the background.
# This is a write operation.\nstore[\"key\"] = value\n# This is also a write operation (it changes the stored data).\ndel store[\"key\"]\n
Should you wish to be certain changes have been synchronized to the underlying IndexDB, just await store.sync()
.
Common types of value can be stored via this API: bool
, float
, int
, str
and None
. In addition, data structures like list
, dict
and tuple
can be stored.
Warning
Because of the way the underlying data structure are stored in IndexDB, a Python tuple
will always be returned as a Python list
.
It is even possible to store arbitrary data via a bytearray
or memoryview
object. However, there is a limitation that such values must be stored as a single key/value pair, and not as part of a nested data structure.
Sometimes you may need to modify the behaviour of the dict
like object returned by pyscript.storage
. To do this, create a new class that inherits from pyscript.Storage
, then pass in your class to pyscript.storage
as the storage_class
argument:
from pyscript import window, storage, Storage\nclass MyStorage(Storage):\ndef __setitem__(self, key, value):\nsuper().__setitem__(key, value)\nwindow.console.log(key, value)\n...\nstore = await storage(\"my-data-store\", storage_class=MyStorage)\n# The store object is now an instance of MyStorage.\n
"},{"location":"api/#pyscriptcorediststoragejs","title":"@pyscript/core/dist/storage.js
","text":"The equivalent functionality based on the JS module can be found through our module.
The goal is to be able to share the same database across different worlds (interpreters) and the functionality is nearly identical except there is no class to provide because the storage in JS is just a dictionary proxy that synchronizes behind the scene all read, write or delete operations.
"},{"location":"api/#pyscriptweb","title":"pyscript.web
","text":"The classes and references in this namespace provide a Pythonic way to interact with the DOM. An explanation for how to idiomatically use this API can be found in the user guide
"},{"location":"api/#pyscriptwebpage","title":"pyscript.web.page
","text":"This object represents a web page. It has four attributes and two methods:
html
- a reference to a Python object representing the document's html root element.head
- a reference to a Python object representing the document's head.body
- a reference to a Python object representing the document's body.title
- the page's title (usually displayed in the browser's title bar or a page's tab.find
- a method that takes a single selector argument and returns a collection of Python objects representing the matching elements.append
- a shortcut for page.body.append
(to add new elements to the page).You may also shortcut the find
method by enclosing a CSS selector in square brackets: page[\"#my-thing\"]
.
These are provided as a convenience so you have several simple and obvious options for accessing and changing the content of the page.
All the Python objects returned by these attributes and method are instances of classes relating to HTML elements defined in the pyscript.web
namespace.
pyscript.web.*
","text":"There are many classes in this namespace. Each is a one-to-one mapping of any HTML element name to a Python class representing the HTML element of that name. Each Python class ensures only valid properties and attributes can be assigned, according to web standards.
Usage of these classes is explained in the user guide.
Info
The full list of supported element/class names is:
grid\na, abbr, address, area, article, aside, audio\nb, base, blockquote, body, br, button\ncanvas, caption, cite, code, col, colgroup\ndata, datalist, dd, del_, details, dialog, div, dl, dt\nem, embed\nfieldset, figcaption, figure, footer, form\nh1, h2, h3, h4, h5, h6, head, header, hgroup, hr, html\ni, iframe, img, input_, ins\nkbd\nlabel, legend, li, link\nmain, map_, mark, menu, meta, meter\nnav\nobject_, ol, optgroup, option, output\np, param, picture, pre, progress\nq\ns, script, section, select, small, source, span, strong, style, sub, summary, sup\ntable, tbody, td, template, textarea, tfoot, th, thead, time, title, tr, track\nu, ul\nvar, video\nwbr\n
These correspond to the standard HTML elements with the caveat that del_
and input_
have the trailing underscore (_
) because they are also keywords in Python, and the grid
is a custom class for a div
with a grid
style display
property.
All these classes ultimately derive from the pyscript.web.elements.Element
base class.
In addition to properties defined by the HTML standard for each type of HTML element (e.g. title
, src
or href
), all elements have the following properties and methods (in alphabetical order):
append(child)
- add the child
element to the element's children.children
- a collection containing the element's child elements (that it contains).classes
- a set of CSS classes associated with the element.clone(clone_id=None)
- Make a clone of the element (and the underlying DOM object), and assign it the optional clone_id
.find(selector)
- use a CSS selector to find matching child elements.parent
- the element's parent element (that contains it).show_me
- scroll the element into view.style
- a dictionary of CSS style properties associated with the element.update(classes=None, style=None, **kwargs)
- update the element with the specified classes (set), style (dict) and DOM properties (kwargs)._dom_element
- a reference to the proxy object that represents the underlying native HTML element.Info
All elements, by virtue of inheriting from the base Element
class, may have the following properties:
accesskey, autofocus, autocapitalize,\nclassName, contenteditable,\ndraggable,\nenterkeyhint,\nhidden,\ninnerHTML, id,\nlang,\nnonce,\npart, popover,\nslot, spellcheck,\ntabindex, text, title, translate,\nvirtualkeyboardpolicy\n
The classes
set-like object has the following convenience functions:
add(*class_names)
- add the class(es) to the element.contains(class_name)
- indicate if class_name
is associated with the element.remove(*class_names)
- remove the class(es) from the element.replace(old_class, new_class)
- replace the old_class
with new_class
.toggle(class_name)
- add a class if it is absent, or remove a class if it is present.Elements that require options (such as the datalist
, optgroup
and select
elements), can have options passed in when they are created:
my_select = select_(option(\"apple\", value=1), option(\"pear\"))\n
Notice how options can be a tuple of two values (the name and associated value) or just the single name (whose associated value will default to the given name).
It's possible to access and manipulate the options
of the resulting elements:
selected_option = my_select.options.selected\nmy_select.options.remove(0) # Remove the first option (in position 0).\nmy_select.clear()\nmy_select.options.add(html=\"Orange\")\n
Finally, the collection of elements returned by find
and children
is iterable, indexable and sliceable:
for child in my_element.children[10:]:\nprint(child.html)\n
Furthermore, four attributes related to all elements contained in the collection can be read (as a list) or set (applied to all contained elements):
classes
- the list of classes associated with the elements.innerHTML
- the innerHTML of each element.style
- a dictionary like object for interacting with CSS style rules.value
- the value
attribute associated with each element.pyscript.when
","text":"A Python decorator to indicate the decorated function should handle the specified events for selected elements.
The decorator takes two parameters:
event_type
should be the name of the browser event to handle as a string (e.g. \"click\"
).selector
should be a string containing a valid selector to indicate the target elements in the DOM whose events of event_type
are of interest.The following example has a button with an id of my_button
and a decorated function that handles click
events dispatched by the button.
<button id=\"my_button\">Click me!</button>\n
The decorated Python function to handle click eventsfrom pyscript import when, display\n@when(\"click\", \"#my_button\")\ndef click_handler(event):\n\"\"\"\n Event handlers get an event object representing the activity that raised\n them.\n \"\"\"\ndisplay(\"I've been clicked!\")\n
This functionality is related to the py-*
or mpy-*
HTML attributes.
pyscript.window
","text":"On the main thread, this object is exactly the same as import js
which, in turn, is a proxy of JavaScript's globalThis object.
On a worker thread, this object is a proxy for the web page's global window context.
Warning
The reference for pyscript.window
is always a reference to the main thread's global window context.
If you're running code in a worker this is not the worker's own global context. A worker's global context is always reachable via import js
(the js
object being a proxy for the worker's globalThis
).
pyscript.HTML
","text":"A class to wrap generic content and display it as un-escaped HTML on the page.
The HTML class<script type=\"mpy\">\nfrom pyscript import display, HTML\n# Escaped by default:\ndisplay(\"<em>em</em>\") # <em>em</em>\n</script>\n<script type=\"mpy\">\nfrom pyscript import display, HTML\n# Un-escaped raw content inserted into the page:\ndisplay(HTML(\"<em>em</em>\")) # <em>em</em>\n</script>\n
"},{"location":"api/#pyscriptrunning_in_worker","title":"pyscript.RUNNING_IN_WORKER
","text":"This constant flag is True
when the current code is running within a worker. It is False
when the code is running within the main thread.
pyscript.WebSocket
","text":"If a pyscript.fetch
results in a call and response HTTP interaction with a web server, the pyscript.Websocket
class provides a way to use websockets for two-way sending and receiving of data via a long term connection with a web server.
PyScript's implementation, available in both the main thread and a web worker, closely follows the browser's own WebSocket class.
This class accepts the following named arguments:
url
pointing at the ws or wss address. E.g.: WebSocket(url=\"ws://localhost:5037/\")
protocols
, an optional string or a list of strings as described here.The WebSocket
class also provides these convenient static constants:
WebSocket.CONNECTING
(0
) - the ws.readyState
value when a web socket has just been created.WebSocket.OPEN
(1
) - the ws.readyState
value once the socket is open.WebSocket.CLOSING
(2
) - the ws.readyState
after ws.close()
is explicitly invoked to stop the connection.WebSocket.CLOSED
(3
) - the ws.readyState
once closed.A WebSocket
instance has only 2 methods:
ws.send(data)
- where data
is either a string or a Python buffer, automatically converted into a JavaScript typed array. This sends data via the socket to the connected web server.ws.close(code=0, reason=\"because\")
- which optionally accepts code
and reason
as named arguments to signal some specific status or cause for closing the web socket. Otherwise ws.close()
works with the default standard values.A WebSocket
instance also has the fields that the JavaScript WebSocket
instance will have:
send()
but not yet transmitted to the network.WebSocket
static constants (CONNECTING
, OPEN
, etc...).WebSocket
instance.A WebSocket
instance can have the following listeners. Directly attach handler functions to them. Such functions will always receive a single event
object.
WebSocket
's connection is closed.WebSocket
. If the event.data
is a JavaScript typed array instead of a string, the reference it will point directly to a memoryview of the underlying bytearray
data.The following code demonstrates a pyscript.WebSocket
in action.
<script type=\"mpy\" worker>\nfrom pyscript import WebSocket\ndef onopen(event):\nprint(event.type)\nws.send(\"hello\")\ndef onmessage(event):\nprint(event.type, event.data)\nws.close()\ndef onclose(event):\nprint(event.type)\nws = WebSocket(url=\"ws://localhost:5037/\")\nws.onopen = onopen\nws.onmessage = onmessage\nws.onclose = onclose\n</script>\n
Info
It's also possible to pass in any handler functions as named arguments when you instantiate the pyscript.WebSocket
class:
from pyscript import WebSocket\ndef onmessage(event):\nprint(event.type, event.data)\nws.close()\nws = WebSocket(url=\"ws://example.com/socket\", onmessage=onmessage)\n
"},{"location":"api/#pyscriptjs_import","title":"pyscript.js_import
","text":"If a JavaScript module is only needed under certain circumstances, we provide an asynchronous way to import packages that were not originally referenced in your configuration.
A pyscript.js_import example.<script type=\"py\">\nfrom pyscript import js_import, window\nescaper, = await js_import(\"https://esm.run/html-escaper\")\n\nwindow.console.log(escaper)\n
The js_import
call returns an asynchronous tuple containing the JavaScript modules referenced as string arguments.
pyscript.py_import
","text":"Warning
This is an experimental feature.
Feedback and bug reports are welcome!
If you have a lot of Python packages referenced in your configuration, startup performance may be degraded as these are downloaded.
If a Python package is only needed under certain circumstances, we provide an asynchronous way to import packages that were not originally referenced in your configuration.
A pyscript.py_import example.<script type=\"py\">\nfrom pyscript import py_import\nmatplotlib, regex, = await py_import(\"matplotlib\", \"regex\")\nprint(matplotlib, regex)\n</script>\n
The py_import
call returns an asynchronous tuple containing the Python modules provided by the packages referenced as string arguments.
pyscript.PyWorker
","text":"A class used to instantiate a new worker from within Python.
Note
Sometimes we disambiguate between interpreters through naming conventions (e.g. py
or mpy
).
However, this class is always PyWorker
and the desired interpreter MUST be specified via a type
option. Valid values for the type of interpreter are either micropython
or pyodide
.
The following fragments demonstrate how to evaluate the file worker.py
on a new worker from within Python.
from pyscript import RUNNING_IN_WORKER, display, sync\ndisplay(\"Hello World\", target=\"output\", append=True)\n# will log into devtools console\nprint(RUNNING_IN_WORKER) # True\nprint(\"sleeping\")\nsync.sleep(1)\nprint(\"awake\")\n
main.py - starts a new worker in Python.from pyscript import PyWorker\n# type MUST be either `micropython` or `pyodide`\nPyWorker(\"worker.py\", type=\"micropython\")\n
The HTML context for the worker.<script type=\"mpy\" src=\"./main.py\">\n<div id=\"output\"></div> <!-- The display target -->\n
"},{"location":"api/#pyscriptworkers","title":"pyscript.workers
","text":"The pyscript.workers
reference allows Python code in the main thread to easily access named workers (and their exported functionality).
For example, the following Pyodide code may be running on a named worker (see the name
attribute of the script
tag):
<script type=\"py\" worker name=\"py-version\">\nimport sys\ndef version():\nreturn sys.version\n# define what to export to main consumers\n__export__ = [\"version\"]\n</script>\n
While over on the main thread, this fragment of MicroPython will be able to access the worker's version
function via the workers
reference:
<script type=\"mpy\">\nfrom pyscript import workers\npyworker = await workers[\"py-version\"]\n# print the pyodide version\nprint(await pyworker.version())\n</script>\n
Importantly, the workers
reference will NOT provide a list of known workers, but will only await
for a reference to a named worker (resolving when the worker is ready). This is because the timing of worker startup is not deterministic.
Should you wish to await for all workers on the page at load time, it's possible to loop over matching elements in the document like this:
<script type=\"mpy\">\nfrom pyscript import document, workers\nfor el in document.querySelectorAll(\"[type='py'][worker][name]\"):\nawait workers[el.getAttribute('name')]\n# ... rest of the code\n</script>\n
"},{"location":"api/#worker-only-features","title":"Worker only features","text":""},{"location":"api/#pyscriptsync","title":"pyscript.sync
","text":"A function used to pass serializable data from workers to the main thread.
Imagine you have this code on the main thread:
Python code on the main threadfrom pyscript import PyWorker\ndef hello(name=\"world\"):\ndisplay(f\"Hello, {name}\")\nworker = PyWorker(\"./worker.py\")\nworker.sync.hello = hello\n
In the code on the worker, you can pass data back to handler functions like this:
Pass data back to the main thread from a workerfrom pyscript import sync\nsync.hello(\"PyScript\")\n
"},{"location":"api/#html-attributes","title":"HTML attributes","text":"As a convenience, and to ensure backwards compatibility, PyScript allows the use of inline event handlers via custom HTML attributes.
Warning
This classic pattern of coding (inline event handlers) is no longer considered good practice in web development circles.
We include this behaviour for historic reasons, but the folks at Mozilla have a good explanation of why this is currently considered bad practice.
These attributes, expressed as py-*
or mpy-*
attributes of an HTML element, reference the name of a Python function to run when the event is fired. You should replace the *
with the actual name of an event (e.g. py-click
or mpy-click
). This is similar to how all event handlers on elements start with on
in standard HTML (e.g. onclick
). The rule of thumb is to simply replace on
with py-
or mpy-
and then reference the name of a Python function.
<button py-click=\"handle_click\" id=\"my_button\">Click me!</button>\n
The related Python function.from pyscript import window\ndef handle_click(event):\n\"\"\"\n Simply log the click event to the browser's console.\n \"\"\"\nwindow.console.log(event) \n
Under the hood, the pyscript.when
decorator is used to enable this behaviour.
Note
In earlier versions of PyScript, the value associated with the attribute was simply evaluated by the Python interpreter. This was unsafe: manipulation of the attribute's value could have resulted in the evaluation of arbitrary code.
This is why we changed to the current behaviour: just supply the name of the Python function to be evaluated, and PyScript will do this safely.
"},{"location":"beginning-pyscript/","title":"Beginning PyScript","text":"PyScript is a platform for running Python in modern web browsers.
Create apps with a PyScript development environment: write code, curate the project's assets, and test your application.
To distribute a PyScript application, host it on the web, then click on the link to your application. PyScript and the browser do the rest.
This page covers these core aspects of PyScript in a beginner friendly manner. We only assume you know how to use a browser and edit text.
Note
The easiest way to get a PyScript development environment and hosting, is to use pyscript.com in your browser.
It is a free service that helps you create new projects from templates, and then edit, preview and deploy your apps with a unique link.
While the core features of pyscript.com will always be free, additional paid-for capabilities directly support and sustain the PyScript open source project. Commercial and educational support is also available.
"},{"location":"beginning-pyscript/#an-application","title":"An application","text":"All PyScript applications need three things:
index.html
file that is served to your browser.pyscript.json
or pyscript.toml
file.main.py
) that defines how your application works.Create these files with your favourite code editor on your local file system. Alternatively, pyscript.com will take away all the pain of organising, previewing and deploying your application.
If you're using your local file system, you'll need a way to view your application in your browser. If you already have Python installed on your local machine, serve your files with the following command run from your terminal and in the same directory as your files:
python3 -m http.server\n
Point your browser at http://localhost:8000. Remember to refresh the page (CTRL-R
) to see any updates you may have made.
Note
If you're using VSCode as your editor, the Live Server extension can be used to reload the page as you edit your files.
Alternatively, if you have an account on GitHub you could use VSCode in your browser as a PyScript aware \"CodeSpace\" (just follow the instructions in the README file).
If you decide to use pyscript.com (recommended for first steps), once signed in, create a new project by pressing the \"+\" button on the left hand side below the site's logo. You'll be presented with a page containing three columns (listing your files, showing your code and previewing the app). The \"save\" and \"run\" buttons do exactly what you'd expect.
Let's build a simple PyScript application that translates English \ud83c\uddec\ud83c\udde7 into Pirate \ud83c\udff4\u200d\u2620\ufe0f speak. In order to do this we'll make use of the arrr library. By building this app you'll be introduced to all the core concepts of PyScript at an introductory level.
You can see this application embedded into the page below (try it out!):
Let's explore each of the three files that make this app work.
"},{"location":"beginning-pyscript/#pyscriptjson","title":"pyscript.json","text":"This file tells PyScript and your browser about various configurable aspects of your application. Put simply, it tells PyScript what it needs in order to run your application. The only thing we need to show is that we require the third party arrr
module to do the actual translation.
We do this by putting arrr
as the single entry in a list of required packages
, so the content of pyscript.json
looks like this:
{\n\"packages\": [\"arrr\"]\n}\n
"},{"location":"beginning-pyscript/#indexhtml","title":"index.html","text":"Next we come to the index.html
file that is first served to your browser.
To start out, we need to tell the browser that this HTML document uses PyScript, and so we create a <script>
tag that references the PyScript module in the document's <head>
tag:
<!DOCTYPE html>\n<html>\n<head>\n<meta charset=\"utf-8\" />\n<meta name=\"viewport\" content=\"width=device-width,initial-scale=1\" />\n<title>\ud83e\udd9c Polyglot - Piratical PyScript</title>\n<link rel=\"stylesheet\" href=\"https://pyscript.net/releases/2024.9.1/core.css\">\n<script type=\"module\" src=\"https://pyscript.net/releases/2024.9.1/core.js\"></script>\n</head>\n<body>\n<!-- TODO: Fill in our custom application code here... -->\n</body>\n</html>\n
Notice that the <body>
of the document is empty except for the TODO comment. It's in here that we put standard HTML content to define our user interface, so the <body>
now looks like:
<body>\n<h1>Polyglot \ud83e\udd9c \ud83d\udcac \ud83c\uddec\ud83c\udde7 \u27a1\ufe0f \ud83c\udff4\u200d\u2620\ufe0f</h1>\n<p>Translate English into Pirate speak...</p>\n<input type=\"text\" name=\"english\" id=\"english\" placeholder=\"Type English here...\" />\n<button py-click=\"translate_english\">Translate</button>\n<div id=\"output\"></div>\n<script type=\"py\" src=\"./main.py\" config=\"./pyscript.json\"></script>\n</body>\n
This fragment of HTML contains the application's header (<h1>
), some instructions between the <p>
tags, an <input>
box for the English text, and a <button>
to click to generate the translation. Towards the end there's a <div id=\"output\">
which will contain the resulting pirate speak as the application's output.
There's something strange about the <button>
tag: it has a py-click
attribute with the value translate_english
. This is, in fact, the name of a Python function we'll run whenever the button is clicked. Such py-*
style attributes are built into PyScript.
We put all this together in the script
tag at the end of the <body>
. This tells the browser we're using PyScript (type=\"py\"
), and where PyScript should find the Python source code (src=\"./main.py\"
). Finally, we indicate where PyScript should find the configuration (config=\"./pyscript.json\"
).
In the end, our HTML should look like this:
index.html<!DOCTYPE html>\n<html>\n<head>\n<meta charset=\"utf-8\" />\n<meta name=\"viewport\" content=\"width=device-width,initial-scale=1\" />\n<title>\ud83e\udd9c Polyglot - Piratical PyScript</title>\n<link rel=\"stylesheet\" href=\"https://pyscript.net/releases/2024.9.1/core.css\">\n<script type=\"module\" src=\"https://pyscript.net/releases/2024.9.1/core.js\"></script>\n</head>\n<body>\n<h1>Polyglot \ud83e\udd9c \ud83d\udcac \ud83c\uddec\ud83c\udde7 \u27a1\ufe0f \ud83c\udff4\u200d\u2620\ufe0f</h1>\n<p>Translate English into Pirate speak...</p>\n<input type=\"text\" id=\"english\" placeholder=\"Type English here...\" />\n<button py-click=\"translate_english\">Translate</button>\n<div id=\"output\"></div>\n<script type=\"py\" src=\"./main.py\" config=\"./pyscript.json\"></script>\n</body>\n</html>\n
But this only defines how the user interface should look. To define its behaviour we need to write some Python. Specifically, we need to define the translate_english
function, used when the button is clicked.
The behaviour of the application is defined in main.py
. It looks like this:
import arrr\nfrom pyscript import document\ndef translate_english(event):\ninput_text = document.querySelector(\"#english\")\nenglish = input_text.value\noutput_div = document.querySelector(\"#output\")\noutput_div.innerText = arrr.translate(english)\n
It's not very complicated Python code.
On line 1 the arrr
module is imported so we can do the actual English to Pirate translation. If we hadn't told PyScript to download the arrr
module in our pyscript.json
configuration file, this line would cause an error. PyScript has ensured our environment is set up with the expected arrr
module.
Line 2 imports the document
object. The document
allows us to reach into the things on the web page defined in index.html
.
Finally, on line 5 the translate_english
function is defined.
The translate_english
function takes a single parameter called event
. This represents the user's click of the button (but which we don't actually use).
Inside the body of the function we first get a reference to the input
element with the document.querySelector
function that takes #english
as its parameter (indicating we want the element with the id \"english\"). We assign the result to input_text
, then extract the user's english
from the input_text
's value
. Next, we get a reference called output_div
that points to the div
element with the id \"output\". Finally, we assign the innerText
of the output_div
to the result of calling arrr.translate
(to actually translate the english
to something piratical).
That's it!
"},{"location":"beginning-pyscript/#sharing-your-app","title":"Sharing your app","text":""},{"location":"beginning-pyscript/#pyscriptcom","title":"PyScript.com","text":"If you're using pyscript.com, you should save all your files and click the \"run\" button. Assuming you've copied the code properly, you should have a fine old time using \"Polyglot \ud83e\udd9c\" to translate English to Pirate-ish.
Alternatively, click here to see a working example of this app. Notice that the bottom right hand corner contains a link to view the code on pyscript.com. Why not explore the code, copy it to your own account and change it to your satisfaction?
"},{"location":"beginning-pyscript/#from-a-web-server","title":"From a web server","text":"Just host the three files (pyscript.json
, index.html
and main.py
) in the same directory on a static web server somewhere.
Clearly, we recommend you use pyscript.com for this, but any static web host will do (for example, GitHub Pages, Amazon's S3, Google Cloud or Microsoft's Azure).
"},{"location":"beginning-pyscript/#run-pyscript-offline","title":"Run PyScript Offline","text":"To run PyScript offline, without the need of a CDN or internet connection, read the Run PyScript Offline section of the user guide.
"},{"location":"beginning-pyscript/#conclusion","title":"Conclusion","text":"Congratulations!
You have just created your first PyScript app. We've explored the core concepts needed to build yet more interesting things of your own.
PyScript is extremely powerful, and these beginner steps only just scratch the surface. To learn about PyScript in more depth, check out our user guide or explore our example applications.
"},{"location":"conduct/","title":"Code of Conduct","text":"Our code of conduct is based on the Contributor Covenant code of conduct.
"},{"location":"conduct/#our-pledge","title":"Our Pledge","text":"We as members, contributors, and leaders pledge to make participation in our community a harassment-free experience for everyone, regardless of age, body size, visible or invisible disability, ethnicity, sex characteristics, gender identity and expression, level of experience, education, socio-economic status, nationality, personal appearance, race, religion, or sexual identity and orientation.
We pledge to act and interact in ways that contribute to an open, welcoming, diverse, inclusive, and healthy community.
"},{"location":"conduct/#our-standards","title":"Our Standards","text":"Examples of behavior that contributes to a positive environment for our community include:
Examples of unacceptable behavior include:
Community leaders are responsible for clarifying and enforcing our standards of acceptable behavior and will take appropriate and fair corrective action in response to any behavior that they deem inappropriate, threatening, offensive, or harmful.
Community leaders have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, and will communicate reasons for moderation decisions when appropriate.
"},{"location":"conduct/#scope","title":"Scope","text":"This Code of Conduct applies within all community spaces, and also applies when an individual is officially representing the community in public spaces. Examples of representing our community include using an official e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event.
"},{"location":"conduct/#enforcement","title":"Enforcement","text":"Instances of abusive, harassing, or otherwise unacceptable behavior may be reported to the community leaders responsible for enforcement as set forth in the repository's Notice.md file. All complaints will be reviewed and investigated promptly and fairly.
All community leaders are obligated to respect the privacy and security of the reporter of any incident.
"},{"location":"conduct/#enforcement-guidelines","title":"Enforcement Guidelines","text":"Community leaders will follow these Community Impact Guidelines in determining the consequences for any action they deem in violation of this Code of Conduct:
"},{"location":"conduct/#1-correction","title":"1. Correction","text":"Community Impact: Use of inappropriate language or other behavior deemed unprofessional or unwelcome in the community.
Consequence: A private, written warning from community leaders, providing clarity around the nature of the violation and an explanation of why the behavior was inappropriate. A public apology may be requested.
"},{"location":"conduct/#2-warning","title":"2. Warning","text":"Community Impact: A violation through a single incident or series of actions.
Consequence: A warning with consequences for continued behavior. No interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, for a specified period of time. This includes avoiding interactions in community spaces as well as external channels like social media. Violating these terms may lead to a temporary or permanent ban.
"},{"location":"conduct/#3-temporary-ban","title":"3. Temporary Ban","text":"Community Impact: A serious violation of community standards, including sustained inappropriate behavior.
Consequence: A temporary ban from any sort of interaction or public communication with the community for a specified period of time. No public or private interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, is allowed during this period. Violating these terms may lead to a permanent ban.
"},{"location":"conduct/#4-permanent-ban","title":"4. Permanent Ban","text":"Community Impact: Demonstrating a pattern of violation of community standards, including sustained inappropriate behavior, harassment of an individual, or aggression toward or disparagement of classes of individuals.
Consequence: A permanent ban from any sort of public interaction within the project community.
"},{"location":"conduct/#reporting-a-violation","title":"Reporting a violation","text":"To report a violation of the Code of Conduct, e-mail conduct@pyscript.net
"},{"location":"conduct/#attribution","title":"Attribution","text":"This Code of Conduct is adapted from the Contributor Covenant, version 2.0, available at https://www.contributor-covenant.org/version/2/0/code_of_conduct.html.
Community Impact Guidelines were inspired by Mozilla's code of conduct enforcement ladder.
For answers to common questions about this code of conduct, see the FAQ at https://www.contributor-covenant.org/faq. Translations are available at https://www.contributor-covenant.org/translations.
"},{"location":"contributing/","title":"Contributing","text":"Thank you for wanting to contribute to the PyScript project!
"},{"location":"contributing/#code-of-conduct","title":"Code of conduct","text":"The PyScript Code of Conduct governs the project and everyone participating in it. By participating, you are expected to uphold this code. Please report unacceptable behavior to the maintainers or administrators as described in that document.
"},{"location":"contributing/#ways-to-contribute","title":"Ways to contribute","text":""},{"location":"contributing/#report-bugs","title":"Report bugs","text":"Bugs are tracked on the project issues page.
Check first
Please check your bug has not already been reported by someone else by searching the existing issues before filing a new one. Once your issue is filed, it will be triaged by another contributor or maintainer. If there are questions raised about your issue, please respond promptly.
If it is not appropriate to submit a security issue using the above process, please e-mail us at security@pyscript.net.
"},{"location":"contributing/#ask-questions","title":"Ask questions","text":"If you have questions about the project, using PyScript, or anything else, please ask in the project's discord server.
"},{"location":"contributing/#create-resources","title":"Create resources","text":"Folks make all sorts of wonderful things with PyScript.
If you have an interesting project, a cool hack, or an innovative way to implement a new capability or feature, please share your work and tell us about it so we can celebrate and amplify your contribution.
Please reach out to us if you'd like advice and feedback.
"},{"location":"contributing/#participate","title":"Participate","text":"As an open source project, PyScript has community at its core. In addition to the ways to engage already outlined, you could join our live community calls.
Announcement of connection details is made via the PyScript discord server.
"},{"location":"contributing/#technical-contributions","title":"Technical contributions","text":"In addition to working with PyScript, if you would like to contribute to PyScript itself, the following advice should be followed.
"},{"location":"contributing/#places-to-start","title":"Places to start","text":"If you're not sure where to begin, we have some suggestions:
We assume you are familiar with core development practices such as using a code editor, writing Python and/or JavaScript and working with tools and services such as GIT and GitHub.
git clone https://github.com/<your username>/pyscript\n
upstream
.git remote add upstream https://github.com/pyscript/pyscript.git\n
git pull upstream main\n
PyScrcipt welcomes contributions, suggestions, and feedback. All contributions, suggestions, and feedback you submitted are accepted under the Apache 2.0 license. You represent that if you do not own copyright in the code that you have the authority to submit it under the Apache 2.0 license. All feedback, suggestions, or contributions are not confidential.
"},{"location":"contributing/#becoming-a-maintainer","title":"Becoming a maintainer","text":"Contributors are invited to be maintainers of the project by demonstrating good decision making in their contributions, a commitment to the goals of the project, and consistent adherence to the code of conduct. New maintainers are invited by a 3/4 vote of the existing maintainers.
"},{"location":"contributing/#trademarks","title":"Trademarks","text":"The Project abides by the Organization's trademark policy.
"},{"location":"developers/","title":"Developer Guide","text":"This page explains the technical and practical requirements and processes needed to contribute to PyScript.
Info
In the following instructions, we assume familiarity with git
, GitHub, the command line and other common development concepts, tools and practices.
For those who come from a non-Pythonic technical background (for example, you're a JavaScript developer), we will explain Python-isms as we go along so you're contributing with confidence.
If you're unsure, or encounter problems, please ask for help on our discord server.
"},{"location":"developers/#welcome","title":"Welcome","text":"We are a diverse, inclusive coding community and welcome contributions from anyone irrespective of their background. If you're thinking, \"but they don't mean me\", then we especially mean YOU. Our diversity means you will meet folks in our community who are different to yourself. Therefore, thoughtful contributions made in good faith, and engagement with respect, care and compassion wins every time.
All contributors are expected to follow our code of conduct.
"},{"location":"developers/#setup","title":"Setup","text":"You must have recent versions of Python, node.js and npm already installed on your system.
The following steps create a working development environment for PyScript. It is through this environment that you contribute to PyScript.
Danger
The following commands work on Unix like operating systems (like MacOS or Linux). If you are a Microsoft Windows user please use the Windows Subsystem for Linux with the following instructions.
"},{"location":"developers/#create-a-virtual-environment","title":"Create a virtual environment","text":"A Python virtual environment is a computing \"sandbox\" that safely isolates your work. PyScript's development makes use of various Python based tools, so both Python and a virtual environment is needed. There are many tools to help manage these environments, but the standard way to create a virtual environment is to use this command in your terminal:
python3 -m venv my_pyscript_dev_venv\n
Warning
Replace my_pyscript_dev_venv
with a meaningful name for the virtual environment, that works for you.
A my_pyscript_dev_venv
directory containing the virtual environment's \"stuff\" is created as a subdirectory of your current directory. Next, activate the virtual environment to ensure your development activities happen within the context of the sandbox:
source my_pyscript_dev_venv/bin/activate\n
The prompt in your terminal will change to include the name of your virtual environment indicating the sandbox is active. To deactivate the virtual environment just type the following into your terminal:
deactivate\n
Info
The rest of the instructions on this page assume you are working in an activated virtual environment for developing PyScript.
"},{"location":"developers/#prepare-your-repository","title":"Prepare your repository","text":"Clone your newly forked version of the PyScript repository onto your local development machine. For example, use this command in your terminal:
git clone https://github.com/<YOUR USERNAME>/pyscript\n
Warning
In the URL for the forked PyScript repository, remember to replace <YOUR USERNAME>
with your actual GitHub username.
Tip
To help explain steps, we will use git
commands to be typed into your terminal / command line.
The equivalent of these commands could be achieved through other means (such as GitHub's desktop client). How these alternatives work is beyond the scope of this document.
Change into the root directory of your newly cloned pyscript
repository:
cd pyscript\n
Add the original PyScript repository as your upstream
to allow you to keep your own fork up-to-date with the latest changes:
git remote add upstream https://github.com/pyscript/pyscript.git\n
If the above fails, try this alternative:
git remote remove upstream\ngit remote add upstream git@github.com:pyscript/pyscript.git\n
Pull in the latest changes from the main upstream
PyScript repository:
git pull upstream main\n
Pyscript uses a Makefile
to automate the most common development tasks. In your terminal, type make
to see what it can do. You should see something like this:
There is no default Makefile target right now. Try:\n\nmake setup - check your environment and install the dependencies.\nmake clean - clean up auto-generated assets.\nmake build - build PyScript.\nmake precommit-check - run the precommit checks (run eslint).\nmake test-integration - run all integration tests sequentially.\nmake fmt - format the code.\nmake fmt-check - check the code formatting.\n
To install the required software dependencies for working on PyScript, in your terminal type:
make setup\n
Updates from npm
and then pip
will scroll past telling you about their progress installing the required packages.
Warning
The setup
process checks the versions of Python, node and npm. If you encounter a failure at this point, it's probably because one of these pre-requisits is out of date on your system. Please update!
To ensure consistency of code layout we use tools to both reformat and check the code.
To ensure your code is formatted correctly:
make fmt\n
To check your code is formatted correctly:
make fmt-check\n
Finally, as part of the automated workflow for contributing pull requests pre-commit checks the source code. If this fails revise your PR. To run pre-commit checks locally (before creating the PR):
make precommit-check\n
This may also revise your code formatting. Re-run make precommit-check
to ensure this is the case.
To turn the JavaScript source code found in the pyscript.core
directory into a bundled up module ready for the browser, type:
make build\n
The resulting assets will be in the pyscript.core/dist
directory.
The integration tests for PyScript are started with:
make test-integration\n
Documentation for PyScript (i.e. what you're reading right now), is found in a separate repository: https://github.com/pyscript/docs
The documentation's README
file contains instructions for setting up a development environment and contributing.
We have suggestions for how to contribute to PyScript. Take a read and dive in.
Please make sure you discuss potential contributions before you put in work. We don#t want folks to waste their time or re-invent the wheel.
Technical discussions happen on our discord server and in the discussions section of our GitHub repository.
Every Tuesday is a technical community video call, the details of which are posted onto the discord server. Face to face technical discussions happen here.
Every Wednesday is a non-technical community engagement call, in which we organise how to engage with, grow and nourish our community.
Every two weeks, on a Thursday, is a PyScript FUN call, the details of which are also posted to discord. Project show-and-tells, cool hacks, new features and a generally humorous and creative time is had by all.
A curated list of example applications that demonstrate various features of PyScript can be found on PyScript.com.
The examples are (links take you to the code):
This page contains the most common questions and \"gotchas\" asked on our Discord server, in our community calls, or within our community.
There are two major areas we'd like to explore: common errors and helpful hints.
"},{"location":"faq/#common-errors","title":"Common errors","text":""},{"location":"faq/#reading-errors","title":"Reading errors","text":"If your application doesn't run, and you don't see any error messages on the page, you should check your browser's console.
When reading an error message, the easy way to find out what's going on, most of the time, is to read the last line of the error.
A Pyodide error.Traceback (most recent call last):\n File \"/lib/python311.zip/_pyodide/_base.py\", line 501, in eval_code\n .run(globals, locals)\n ^^^^^^^^^^^^^^^^^^^^\n File \"/lib/python311.zip/_pyodide/_base.py\", line 339, in run\n coroutine = eval(self.code, globals, locals)\n ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n File \"<exec>\", line 1, in <module>\nNameError: name 'failure' is not defined\n\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\n
A MicroPython error.Traceback (most recent call last):\n File \"<stdin>\", line 1, in <module>\nNameError: name 'failure' isn't defined\n\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\n
In both examples, the code created a NameError
because the object with the name failure
did not exist. Everything above the error message is potentially useful technical detail.
With this context in mind, these are the most common errors users of PyScript encounter.
"},{"location":"faq/#sharedarraybuffer","title":"SharedArrayBuffer","text":"This is the first and most common error users may encounter with PyScript:
Failure
Your application doesn't run and in your browser's console you see this message:
Unable to use `window` or `document` -> https://docs.pyscript.net/latest/faq/#sharedarraybuffer\n
"},{"location":"faq/#when","title":"When","text":"This happens when you're unable to access objects in the main thread (window
and document
) from code running in a web worker.
This error happens because the server delivering your PyScript application is incorrectly configured or a service-worker
attribute has not been used in your script
element.
Specifically, one of the following three problem situations applies to your code:
worker
attribute in your script
element, and your Python code uses the window
or document
objects (that actually exist on the main thread), then the browser limitation on Atomics will cause the failure, unless you reconfigure your server.<script type=\"py-editor\">
(that must always use a worker behind the scenes) and no fallback has been provided via a service-worker
attribute on that element.PyWorker
or MPWorker
instance bootstrapping somewhere in your code and no service_worker
fallback has been provided.All these cases have been documented with code examples and possible solutions in our section on web workers.
"},{"location":"faq/#why","title":"Why","text":"The only way for document.getElementById('some-id').value
to work in a worker is to use these two JavaScript primitives:
wait(sab, index)
(sab
is a SharedArrayBuffer
) and notify(sab, index)
to unlock the awaiting thread.While a worker waits for an operation on main to happen, it is not using the CPU. It idles until the referenced index of the shared buffer changes, effectively never blocking the main thread while still pausing its own execution until the buffer's index is changed.
As overwhelming or complicated as this might sound, these two fundamental primitives make main \u2194 worker interoperability an absolute wonder in term of developer experience. Therefore, we encourage folks to prefer using workers over running Python in the main thread. This is especially so when using Pyodide related projects, because of its heavier bootstrap or computation requirements. Using workers ensures the main thread (and thus, the user interface) remains unblocked.
Unfortunately, we can patch, polyfill, or workaround, these primitives but we cannot change their intrinsic nature and limitations defined by web standards. However, there are various solutions for working around such limitations. Please read our web workers section to learn more.
"},{"location":"faq/#borrowed-proxy","title":"Borrowed proxy","text":"This is another common error that happens with listeners, timers or in any other situation where a Python callback is lazily invoked from JavaScript:
Failure
Your application doesn't run and in your browser's console you see this message:
Uncaught Error: This borrowed proxy was automatically destroyed at the end of a function call.\nTry using create_proxy or create_once_callable.\nFor more information about the cause of this error, use `pyodide.setDebug(true)`\n
"},{"location":"faq/#when_1","title":"When","text":"This error happens when using Pyodide as the interpreter on the main thread, and when a bare Python callable/function has been passed into JavaScript as a callback handler:
An expired borrowed proxy example, with Pyodide on the main thread.import js\n# will throw the error\njs.setTimeout(lambda msg: print(msg), 1000, \"FAIL\")\n
The garbage collector immediately cleans up the Python function once it is passed into the JavaScript context. Clearly, for the Python function to work as a callback at some time in the future, it should NOT be garbage collected and hence the error message.
Info
This error does not happen if the code is executed in a worker and the JavaScript reference comes from the main thread:
Code running on Pyodide in a worker has no borrowed proxy issue.from pyscript import window\nwindow.setTimeout(lambda x: print(x), 1000, \"OK\")\n
Proxy objects (i.e. how Python objects appear to JavaScript, and vice versa) cannot be communicated between a worker and the main thread.
Behind the scenes, PyScript ensures references are maintained between workers and the main thread. It means Python functions in a worker are actually represented by JavaScript proxy objects in the main thread.
As a result, such worker based Python functions are therefore not bare Python functions, but already wrapped in a managed JavaScript proxy, thus avoiding the borrowed proxy problem.
If you encounter this problem you have two possible solutions:
pyscript.ffi.create_proxy
.experimental_create_proxy = \"auto\"
flag in your application's settings. This flag intercepts Python objects passed into a JavaScript callback and ensures an automatic and sensible memory management operation via the JavaScript garbage collector.Note
The FinalizationRegistry is the browser feature used to make this so.
By default, it is not observable and it is not possible to predict when it will free, and hence destroy, retained Python proxy objects. As a result, memory consumption might be slightly higher than when manually using create_proxy
. However, the JavaScript engine is responsible for memory consumption, and will cause the finalization registry to free all retained proxies, should memory consumption become too high.
PyScript's interpreters (Pyodide and MicroPython) both have their own garbage collector for automatic memory management. When references to Python objects are passed to JavaScript via the FFI, the Python interpreters cannot guarantee such references will ever be freed by JavaScript's own garbage collector. They may even lose control over the reference since there's no infallible way to know when such objects won't be needed by JavaScript.
One solution is to expect users to explicitly create and destroy such proxy objects themselves. But this manual memory management makes automatic memory management pointless while raising the possibility of dead references (where the user explicitly destroys a Python object that's still alive in the JavaScript context). Put simply, this is a difficult situation.
Pyodide provides ffi.wrappers to help with many of the common cases, and PyScript, through the experimental_create_proxy = \"auto\"
configuration option, automates memory management via the FinalizationRegistry
described above.
Sometimes Python packages, specified via the packages
configuration setting don't work with PyScript's Python interpreter.
Failure
You are using Pyodide.
Your application doesn't run and in your browser's console you see this message:
ValueError: Can't find a pure Python 3 wheel for: 'package_name'\n
Failure
You are using MicroPython.
Your application doesn't run and in your browser's console you see this message:
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the\nremote resource at https://micropython.org/pi/v2/package/py/package_name/latest.json.\n(Reason: CORS header \u2018Access-Control-Allow-Origin\u2019 missing).\nStatus code: 404.\n
"},{"location":"faq/#when_2","title":"When","text":"This is a complicated problem, but the summary is:
micropython-lib
package repository. If you want to use a pure Python package with MicroPython, use the files configuration option to manually copy the package onto the file system, or use a URL to reference the package.For hints and tips about packaging related aspects of PyScript read the packaging pointers section of this FAQ.
"},{"location":"faq/#why_2","title":"Why","text":"Put simply, Pyodide and MicroPython are different Python interpreters, and both are running in a web assembly environment. Packages built for Pyodide may not work for MicroPython, and vice versa. Furthermore, if a package contains compiled code, it may not yet have been natively compiled for web assembly.
If the package you want to use is written in a version of Python that both Pyodide and MicroPython support (there are subtle differences between the interpreters), then you should be able to use the package so long as you are able to get it into the Python path via configuration (see above).
Currently, MicroPython cannot expose modules that require native compilation, but PyScript is working with the MicroPython team to provide different builds of MicroPython that include commonly requested packages (e.g. MicroPython's version of numpy
or sqlite
).
Warning
Depending on the complexity of the project, it may be hard to seamlessly make a 1:1 port from a Pyodide code base to MicroPython.
MicroPython has comprehensive documentation to explain the differences between itself and \"regular\" CPython (i.e. the version of Python Pyodide provides).
"},{"location":"faq/#javascript-modules","title":"JavaScript modules","text":"When using JavaScript modules with PyScript you may encounter the following errors:
Failure
Uncaught SyntaxError: The requested module './library.js' does not provide an export named 'default'
Failure
Uncaught SyntaxError: The requested module './library.js' does not provide an export named 'util'
"},{"location":"faq/#when_3","title":"When","text":"These errors happen because the JavaScript module you are trying to use is not written as a standards-compliant JavaScript module.
Happily, to solve this issue various content delivery networks (CDNs) provide a way to automatically deliver standard ESM (aka: ECMAScript Modules). The one we recommend is esm.run.
An example of esm.run<mpy-config>\n[js_modules.main]\n\"https://esm.run/d3\" = \"d3\"\n</mpy-config>\n<script type=\"mpy\">\nfrom pyscript.js_modules import d3\n</script>\n
Alternatively, ensure any JavaScript code you reference uses export ...
or ask for an .mjs
version of the code. All the various options and technical considerations surrounding the use of JavaScript modules in PyScript are covered in our user guide.
Even though the standard for JavaScript modules has existed since 2015, many old and new libraries still produce files that are incompatible with such modern and idiomatic standards.
This isn't so much a technical problem, as a human problem as folks learn to use the new standard and migrate old code away from previous and now obsolete standards.
While such legacy code exists, be aware that JavaScript code may require special care.
"},{"location":"faq/#possible-deadlock","title":"Possible deadlock","text":"Users may encounter an error message similar to the following:
Failure
\ud83d\udc80\ud83d\udd12 - Possible deadlock if proxy.xyz(...args) is awaited\n
"},{"location":"faq/#when_4","title":"When","text":"This error happens when your code on a worker and in the main thread are in a deadlock. Put simply, neither fragment of code can proceed without waiting for the other.
"},{"location":"faq/#why_4","title":"Why","text":"Let's assume a worker script contains the following Python code:
worker: a deadlock examplefrom pyscript import sync\nsync.worker_task = lambda: print('\ud83d\udd25 this is fine \ud83d\udd25')\n# deadlock \ud83d\udc80\ud83d\udd12\nsync.main_task()\n
On the main thread, let's instead assume this code:
main: a deadlock example<script type=\"mpy\">\nfrom pyscript import PyWorker\ndef async main_task():\n# deadlock \ud83d\udc80\ud83d\udd12\nawait pw.sync.worker_task()\npw = PyWorker(\"./worker.py\", {\"type\": \"pyodide\"})\npw.sync.main_task = main_task\n</script>\n
When the worker bootstraps and calls sync.main_task()
on the main thread, it blocks until the result of this call is returned. Hence it cannot respond to anything at all. However, in the code on the main thread, the sync.worker_task()
in the worker is called, but the worker is blocked! Now the code on both the main thread and worker are mutually blocked and waiting on each other. We are in a classic deadlock situation.
The moral of the story? Don't create such circular deadlocks!
How?
The mutually blocking calls cause the deadlock, so simply don't block.
For example, on the main thread, let's instead assume this code:
main: avoiding deadlocks<script type=\"mpy\">\nfrom pyscript import window, PyWorker\nasync def main_task():\n# do not await the worker,\n# just schedule it for later (as resolved)\nwindow.Promise.resolve(pw.sync.worker_task())\npw = PyWorker(\"./worker.py\", {\"type\": \"pyodide\"})\npw.sync.main_task = main_task\n</script>\n
By scheduling the call to the worker (rather than awaiting it), it's possible for the main thread to call functions defined in the worker in a non-blocking manner, thus allowing the worker to also work in an unblocked manner and react to such calls. We have resolved the mutual deadlock.
"},{"location":"faq/#helpful-hints","title":"Helpful hints","text":"This section contains common hacks or hints to make using PyScript easier.
Note
We have an absolutely lovely PyScript contributor called Jeff Glass who maintains an exceptional blog full of PyScript recipes with even more use cases, hints, tips and solutions. Jeff also has a wonderful YouTube channel full of very engaging PyScript related content.
If you cannot find what you are looking for here, please check Jeff's blog as it's likely he's probably covered something close to the situation in which you find yourself.
Of course, if ever you meet Jeff in person, please buy him a beer and remember to say a big \"thank you\". \ud83c\udf7b
"},{"location":"faq/#pyscript-latest","title":"PyScriptlatest
","text":"PyScript follows the CalVer convention for version numbering.
Put simply, it means each version is numbered according to when, in the calendar, it was released. For instance, version 2024.4.2
was the second release in the month of April in the year 2024 (not the release on the 2nd of April but the second release in April).
It used to be possible to reference PyScript via a version called latest
, which would guarantee you always got the latest release.
However, at the end of 2023, we decided to stop supporting latest
as a way to reference PyScript. We did this for two broad reasons:
latest
, found their applications broke. We want to avoid this at all costs.Therefore, pinning your app's version of PyScript to a specific release (rather than latest
) ensures you get exactly the version of PyScript you used when writing your code.
However, as we continue to develop PyScript it is possible to get our latest development version of PyScript via npm
and we could (should there be enough interest) deliver our work-in-progress via a CDN's \"canary\" or \"development\" channel. We do not guarantee the stability of such versions of PyScript, so never use them in production, and our documentation may not reflect the development version.
If you require the development version of PyScript, these are the URLs to use:
PyScript development. \u26a0\ufe0f\u26a0\ufe0f\u26a0\ufe0f WARNING: HANDLE WITH CARE! \u26a0\ufe0f\u26a0\ufe0f\u26a0\ufe0f<link rel=\"stylesheet\" href=\"https://cdn.jsdelivr.net/npm/@pyscript/core/dist/core.css\">\n<script type=\"module\" src=\"https://cdn.jsdelivr.net/npm/@pyscript/core/dist/core.js\"></script>\n
Warning
Do not use shorter urls or other CDNs.
PyScript needs both the correct headers to use workers and to find its own assets at runtime. Other CDN links might result into a broken experience.
"},{"location":"faq/#workers-via-javascript","title":"Workers via JavaScript","text":"Sometimes you want to start a Pyodide or MicroPython web worker from JavaScript.
Here's how:
Starting a PyScript worker from JavaScript.<script type=\"module\">\n// use sourceMap for @pyscript/core or change to a CDN\nimport {\nPyWorker, // Pyodide Worker\nMPWorker // MicroPython Worker\n} from '@pyscript/core';\nconst worker = await MPWorker(\n// Python code to execute\n'./micro.py',\n// optional details or config with flags\n{ config: { sync_main_only: true } }\n// ^ just as example ^\n);\n// \"heavy computation\"\nawait worker.sync.doStuff();\n// kill the worker when/if needed\nworker.terminate();\n</script>\n
micro.pyfrom pyscript import sync\ndef do_stuff():\nprint(\"heavy computation\")\n# Note: this reference is awaited in the JavaScript code.\nsync.doStuff = do_stuff\n
"},{"location":"faq/#javascript-classnew","title":"JavaScript Class.new()
","text":"When using Python to instantiate a class defined in JavaScript, one needs to use the class's new()
method, rather than just using Class()
(as in Python).
Why?
The reason is technical, related to JavaScript's history and its relatively poor introspection capabilities:
typeof function () {}
and typeof class {}
produce the same outcome: function
. This makes it very hard to disambiguate the intent of the caller as both are valid, JavaScript used to use function
(rather than class
) to instantiate objects, and the class you're using may not use the modern, class
based, idiom.apply
and construct
methods used during instantiation. However, because of the previous point, it's not possible to be sure that apply
is meant to construct
an instance or call a function.Class()
in JavaScript (without the new
operator) throws an error.new Class()
is invalid syntax in Python. So there is still a need to somehow disambiguate the intent to call a function or instantiate a class.Class.new()
to explicitly signal the intent to instantiate a JavaScript class. While not ideal it is clear and unambiguous.PyScript uses hooks during the lifecycle of the application to facilitate the creation of plugins.
Beside hooks, PyScript also dispatches events at specific moments in the lifecycle of the app, so users can react to changes in state:
"},{"location":"faq/#mpyready","title":"m/py:ready","text":"Both the mpy:ready
and py:ready
events are dispatched for every PyScript related element found on the page. This includes <script type=\"py\">
, <py-script>
or any MicroPython/mpy
counterpart.
The m/py:ready
events dispatch immediately before the code is executed, but after the interpreter is bootstrapped.
<script>\naddEventListener(\"py:ready\", () => {\n// show running for an instance\nconst status = document.getElementById(\"status\");\nstatus.textContent = 'running';\n});\n</script>\n<!-- show bootstrapping right away -->\n<div id=\"status\">bootstrapping</div>\n<script type=\"py\" worker>\nfrom pyscript import document\n# show done after running\nstatus = document.getElementById(\"status\")\nstatus.textContent = \"done\"\n</script>\n
A classic use case for this event is to recreate the \"starting up\" spinner that used to be displayed when PyScript bootstrapped. Just show the spinner first, then close it once py:ready
is triggered!
Warning
If using Pyodide on the main thread, the UI will block until Pyodide has finished bootstrapping. The \"starting up\" spinner won't work unless Pyodide is started on a worker instead.
"},{"location":"faq/#mpydone","title":"m/py:done","text":"The mpy:done
and py:done
events dispatch after the either the synchronous or asynchronous code has finished execution.
<script>\naddEventListener(\"py:ready\", () => {\n// show running for an instance\nconst status = document.getElementById(\"status\");\nstatus.textContent = 'running';\n});\naddEventListener(\"py:done\", () => {\n// show done after logging \"Hello \ud83d\udc4b\"\nconst status = document.getElementById(\"status\");\nstatus.textContent = 'done';\n});\n</script>\n<!-- show bootstrapping right away -->\n<div id=\"status\">bootstrapping</div>\n<script type=\"py\" worker>\nprint(\"Hello \ud83d\udc4b\")\n</script>\n
Warning
If async
code contains an infinite loop or some orchestration that keeps it running forever, then these events may never trigger because the code never really finishes.
The py:all-done
event dispatches when all code is finished executing.
This event is special because it depends upon all the MicroPython and Pyodide scripts found on the page, no matter the interpreter.
In this example, MicroPython waves before Pyodide before the \"everything is done\"
message is written to the browser's console.
<script>\naddEventListener(\"py:all-done\", () => {\nconsole.log(\"everything is done\");\n});\n</script>\n<script type=\"mpy\" worker>\nprint(\"MicroPython \ud83d\udc4b\")\n</script>\n<script type=\"py\" worker>\nprint(\"Pyodide \ud83d\udc4b\")\n</script>\n
"},{"location":"faq/#mpyprogress","title":"m/py:progress","text":"The py:progress
or mpy:progress
event triggers on the main thread during interpreter bootstrap (no matter if your code is running on main or in a worker).
The received event.detail
is a string that indicates operations between Loading {what}
and Loaded {what}
. So, the first event would be, for example, Loading Pyodide
and the last one per each bootstrap would be Loaded Pyodide
.
In between all operations are event.detail
s, such as:
Loading files
and Loaded files
, when [files]
is found in the optional configLoading fetch
and Loaded fetch
, when [fetch]
is found in the optional configLoading JS modules
and Loaded JS modules
, when [js_modules.main]
or [js_modules.worker]
is found in the optional configLoading ...
and Loaded ...
events so that users can see what is going on while PyScript is bootstrappingAn example of this listener applied to a dialog can be found in here.
"},{"location":"faq/#packaging-pointers","title":"Packaging pointers","text":"Applications need third party packages and PyScript can be configured to automatically install packages for you. Yet packaging can be a complicated beast, so here are some hints for a painless packaging experience with PyScript.
There are essentially five ways in which a third party package can become available in PyScript.
packages
setting in PyScript. There are plans for MicroPython to offer different builds for PyScript, some to include MicroPython's version of numpy or the API for sqlite.files
setting..zip
or .tgz
/.tar.gz
/.whl
archive to be decompressed into the file system (again, via the files
setting)..whl
package and reference it via a URL in the packages = [...]
list.Just put the package you need somewhere it can be served (like PyScript.com) and reference the URL in the packages
setting. So long as the server at which you are hosting the package allows CORS (fetching files from other domains) everything should just work.
It is even possible to install such packages at runtime, as this example using MicroPython's mip
tool demonstrates (the equivalent can be achieved with Pyodide via micropip
).
# Install default version from micropython-lib\nmip.install(\"keyword\")\n# Install from raw URL\nmip.install(\"https://raw.githubusercontent.com/micropython/micropython-lib/master/python-stdlib/bisect/bisect.py\")\n# Install from GitHub shortcut\nmip.install(\"github:jeffersglass/some-project/foo.py\")\n
"},{"location":"faq/#provide-your-own-file","title":"Provide your own file","text":"One can use the files
setting to copy packages onto the Python path:
<mpy-config>\n[files]\n\"./modules/bisect.py\" = \"./bisect.py\"\n</mpy-config>\n<script type=\"mpy\">\nimport bisect\n</script>\n
"},{"location":"faq/#code-archive-ziptgzwhl","title":"Code archive (zip
/tgz
/whl
)","text":"Compress all the code you want into an archive (using either either zip
or tgz
/tar.gz
). Host the resulting archive and use the files
setting to decompress it onto the Python interpreter's file system.
Consider the following file structure:
my_module/__init__.py\nmy_module/util.py\nmy_module/sub/sub_util.py\n
Host it somewhere, and decompress it into the home directory of the Python interpreter:
A code archive.<mpy-config>\n[files]\n\"./my_module.zip\" = \"./*\"\n</mpy-config>\n<script type=\"mpy\">\nfrom my_module import util\nfrom my_module.sub import sub_util\n</script>\n
Please note, the target folder must end with a star (*
), and will contain everything in the archive. For example, \"./*\"
refers to the home folder for the interpreter.
Python expects a file system. In PyScript each interpreter provides its own in-memory virtual file system. This is not the same as the filesystem on the user's device, but is simply a block of memory in the browser.
Warning
The file system is not persistent nor shareable (yet).
Every time a user loads or stores files, it is done in ephemeral memory associated with the current browser session. Beyond the life of the session, nothing is shared, nothing is stored, nothing persists!
"},{"location":"faq/#readwrite","title":"Read/Write","text":"The easiest way to add content to the virtual file system is by using native Python file operations:
Writing to a text file.with open(\"./test.txt\", \"w\") as dest:\ndest.write(\"hello vFS\")\ndest.close()\n# Read and print the written content.\nwith open(\"./test.txt\", \"r\") as f:\ncontent = f.read()\nprint(content)\n
Combined with our pyscript.fetch
utility, it's also possible to store more complex data from the web.
# Assume async execution.\nfrom pyscript import fetch, window\nhref = window.location.href\nwith open(\"./page.html\", \"wb\") as dest:\ndest.write(await fetch(href).bytearray())\n# Read and print the current HTML page.\nwith open(\"./page.html\", \"r\") as source:\nprint(source.read())\n
"},{"location":"faq/#upload","title":"Upload","text":"It's possible to upload a file onto the virtual file system from the browser (<input type=\"file\">
), and using the DOM API.
The following fragment is just one way to achieve this. It's very simple and builds on the file system examples already seen.
Upload files onto the virtual file system via the browser.<!-- Creates a file upload element on the web page. -->\n<input type=\"file\">\n<!-- Python code to handle file uploads via the HTML input element. -->\n<script type=\"mpy\">\nfrom pyscript import document, fetch, window\nasync def on_change(event):\n# For each file the user has selected to upload...\nfor file in input.files:\n# create a temporary URL,\ntmp = window.URL.createObjectURL(file)\n# fetch and save its content somewhere,\nwith open(f\"./{file.name}\", \"wb\") as dest:\ndest.write(await fetch(tmp).bytearray())\n# then revoke the tmp URL.\nwindow.URL.revokeObjectURL(tmp)\n# Grab a reference to the file upload input element and add\n# the on_change handler (defined above) to process the files.\ninput = document.querySelector(\"input[type=file]\")\ninput.onchange = on_change\n</script>\n
"},{"location":"faq/#download","title":"Download","text":"It is also possible to create a temporary link through which you can download files present on the interpreter's virtual file system.
Download file from the virtual file system.from pyscript import document, ffi, window\nimport os\ndef download_file(path, mime_type):\nname = os.path.basename(path)\nwith open(path, \"rb\") as source:\ndata = source.read()\n# Populate the buffer.\nbuffer = window.Uint8Array.new(len(data))\nfor pos, b in enumerate(data):\nbuffer[pos] = b\ndetails = ffi.to_js({\"type\": mime_type})\n# This is JS specific\nfile = window.File.new([buffer], name, details)\ntmp = window.URL.createObjectURL(file)\ndest = document.createElement(\"a\")\ndest.setAttribute(\"download\", name)\ndest.setAttribute(\"href\", tmp)\ndest.click()\n# here a timeout to window.URL.revokeObjectURL(tmp)\n# should keep the memory clear for the session\n
"},{"location":"faq/#create_proxy","title":"create_proxy","text":"The create_proxy
function is described in great detail on the FFI page, but it's also useful to explain when create_proxy
is needed and the subtle differences between Pyodide and MicroPython.
To call a Python function from JavaScript, the native Python function needs to be wrapped in a JavaScript object that JavaScript can use. This JavaScript object converts and normalises arguments passed into the function before handing off to the native Python function. It also reverses this process with any results from the Python function, and so converts and normalises values before returning the result to JavaScript.
The JavaScript primitive used for this purpose is the Proxy. It enables \"traps\", such as apply, so the extra work required to call the Python function can happen.
Once the apply(target, self, args)
trap is invoked:
self
argument for apply
is probably ignored for most common cases.args
must be resolved and converted into their Python primitive representations or associated Python objects.Ultimately, the targets referenced in the apply
must exist in the Python context so they are ready when the JavaScript apply
method calls into the Python context.
Here's the important caveat: locally scoped Python functions, or functions created at run time cannot be retained forever.
A basic Python to JavaScript callback.import js\njs.addEventListener(\n\"custom:event\",\nlambda e: print(e.type)\n)\n
In this example, the anonymous lambda
function has no reference in the Python context. It's just delegated to the JavaScript runtime via addEventListener
, and then Python immediately garbage collects it. However, as previously mentioned, such a Python object must exist for when the custom:event
is dispatched.
Furthermore, there is no way to define how long the lambda
should be kept alive in the Python environment, nor any way to discover if the custom:event
callback will ever dispatch (so the lambda
is forever pending). PyScript, the browser and the Python interpreters can only work within a finite amount of memory, so memory management and the \"aliveness\" of objects is important.
Therefore, create_proxy
is provided to delegate responsibility for the lifecycle of an object to the author of the code. In other words, wrapping the lambda
in a call to create_proxy
would ensure the Python interpreter retains a reference to the anonymous function for future use.
Info
This probably feels strange! An implementation detail of how the Python and JavaScript worlds interact with each other is bleeding into your code via create_proxy
. Surely, if we always just need to create a proxy, a more elegant solution would be to do this automatically?
As you'll see, this is a complicated situation with inevitable tradeoffs, but ultimately, through the experimental_create_proxy = \"auto\"
flag, you probably never need to use create_proxy
. This section of our docs gives you the context you need to make an informed decision.
However, this isn't the end of the story.
When a Python callback is attached to a specific JavaScript instance (rather than passed as argument into an event listener), it is easy for the Python interpreter to know when the function could be freed from the memory.
A sticky lambda.from pyscript import document\n# logs \"click\" if nothing else stopped propagation\ndocument.onclick = lambda e: print(e.type)\n
\"Wait, wat? This doesn't make sense at all!?!?\", is a valid question/response to this situation.
In this case there's no need to use create_proxy
because the JavaScript reference to which the function is attached isn't going away and the interpreter can use the FinalizationRegistry
to destroy the lambda
(or decrease its reference count) when the underlying JavaScript reference to which it is attached is itself destroyed.
The create_proxy
utility was created (among others) to smooth out and circumvent the afore mentioned memory issues when using Python callables with JavaScript event handlers.
Using it requires special care. The coder must invoke the destroy()
method when the Python callback is no longer needed. It means coders must track the callback's lifecycle. But this is not always possible:
Luckily the Promise
use case is automatically handled by Pyodide, but we're still left with the other cases:
from pyscript import ffi, window\n# The create_proxy is needed when a Python\n# function isn't attached to an object reference\n# (but is, rather, an argument passed into\n# the JavaScript context).\n# This is needed so a proxy is created for\n# future use, even if `print` won't ever need\n# to be freed from the Python runtime.\nwindow.setTimeout(\nffi.create_proxy(print),\n100,\n\"print\"\n)\n# This is needed because the lambda is\n# immediately garbage collected.\nwindow.setTimeout(\nffi.create_proxy(\nlambda x: print(x)\n),\n100,\n\"lambda\"\n)\ndef print_type(event):\nprint(event.type)\n# This is needed even if `print_type`\n# is not a scoped / local function.\nwindow.addEventListener(\n\"some:event\",\nffi.create_proxy(print_type),\n# despite this intent, the proxy\n# will be trapped forever if not destroyed\nffi.to_js({\"once\": True})\n)\n# This does NOT need create_function as it is\n# attached to an object reference, hence observed to free.\nwindow.Object().no_create_function = lambda: print(\"ok\")\n
To simplify this complicated situation PyScript has an experimental_create_proxy = \"auto\"
flag. When set, PyScript intercepts JavaScript callback invocations, such as those in the example code above, and automatically proxies and destroys any references that are garbage collected in the JavaScript environment.
When this flag is set to auto
in your configuration, you should never need to use create_proxy
with Pyodide.
Note
When it comes code running on a web worker, due to the way browser work, no Proxy can survive a round trip to the main thread and back.
In this scenario PyScript works differently and references callbacks via a unique id, rather than by their identity on the worker. When running on a web worker, PyScript automatically frees proxy object references, so you never need to use create_proxy
when running code on a web worker.
The proxy situation is definitely simpler in MicroPython. It just creates proxies automatically (so there is no need for a manual create_proxy
step).
This is because MicroPython doesn't (yet) have a destroy()
method for proxies, rendering the use case of create_proxy
redundant.
Accordingly, the use of create_proxy
in MicroPython is only needed for code portability purposes between Pyodide and MicroPython. When using create_proxy
in MicroPython, it's just a pass-through function and doesn't actually do anything.
All the examples that require create_proxy
in Pyodide, don't need it in MicroPython:
from pyscript import window\n# This just works.\nwindow.setTimeout(print, 100, \"print\")\n# This also just works.\nwindow.setTimeout(lambda x: print(x), 100, \"lambda\")\ndef print_type(event):\nprint(event.type)\n# This just works too.\nwindow.addEventListener(\n\"some:event\",\nprint_type,\nffi.to_js({\"once\": True})\n)\n# And so does this.\nwindow.Object().no_create_function = lambda: print(\"ok\")\n
"},{"location":"faq/#to_js","title":"to_js","text":"Use of the pyodide.ffi.to_js
function is described in the ffi page. But it's also useful to cover the when and why to_js
is needed, if at all.
Despite their apparent similarity, Python dictionaries and JavaScript object literals are very different primitives:
A Python dictionary.ref = {\"some\": \"thing\"}\n# Keys don't need quoting, but only when initialising a dict...\nref = dict(some=\"thing\")\n
A JavaScript object literal.const ref = {\"some\": \"thing\"};\n// Keys don't need quoting, so this is as equally valid...\nconst ref = {some: \"thing\"};\n
In both worlds, accessing ref[\"some\"]
would produce the same result: the string \"thing\"
.
However, in JavaScript ref.some
(i.e. a dotted reference to the key) would also work to return the string \"thing\"
(this is not the case in Python), while in Python ref.get(\"some\")
achieves the same result (and this is not the case in JavaScript).
Perhaps because of this, Pyodide chose to convert Python dictionaries to JavaScript Map objects that share a .get
method with Python.
Unfortunately, in idiomatic JavaScript and for the vast majority of APIs, an object literal (rather than a Map
) is used to represent key/value pairs. Feedback from our users indicates the dissonance of using a Map
rather than the expected object literal to represent a Python dict
is the source of a huge amount of frustration. Sadly, the APIs for Map
and object literals are sufficiently different that one cannot be a drop in replacement for another.
Pyodide have provided a way to override the default Map
based behaviour, but this results some rather esoteric code:
import js\nfrom pyodide.ffi import to_js\njs.callback(\nto_js(\n{\"async\": False},\n# Transform the default Map into an object literal.\ndict_converter=js.Object.fromEntries\n)\n)\n
Info
Thanks to a recent change in Pyodide, such Map
instances are duck-typed to behave like object literals. Conversion may not be needed anymore, and to_js
may just work without the need of the dict_converter
. Please check.
MicroPython's version of to_js
takes the opposite approach (for many of the reasons stated above) and converts Python dictionaries to object literals instead of Map
objects.
As a result, the PyScript pyscript.ffi.to_js
ALWAYS returns a JavaScript object literal by default when converting a Python dictionary no matter if you're using Pyodide or MicroPython as your interpreter. Furthermore, when using MicroPython, because things are closer to idiomatic JavaScript behaviour, you may not even need to use to_js
unless you want to ensure cross-interpreter compatibility.
Warning
When using pyscript.to_js
, the result is detached from the original Python dictionary.
Any change to the JavaScript object will not be reflected in the original Python object. For the vast majority of use cases, this is a desirable trade-off. But it's important to note this detachment.
If you're simply passing data around, pyscript.ffi.to_js
will fulfil your requirements in a simple and idiomatic manner.
Version 2.0, January 2004 <http://www.apache.org/licenses/>
"},{"location":"license/#terms-and-conditions-for-use-reproduction-and-distribution","title":"Terms and Conditions for use, reproduction, and distribution","text":""},{"location":"license/#1-definitions","title":"1. Definitions","text":"\u201cLicense\u201d shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document.
\u201cLicensor\u201d shall mean the copyright owner or entity authorized by the copyright owner that is granting the License.
\u201cLegal Entity\u201d shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, \u201ccontrol\u201d means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity.
\u201cYou\u201d (or \u201cYour\u201d) shall mean an individual or Legal Entity exercising permissions granted by this License.
\u201cSource\u201d form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files.
\u201cObject\u201d form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types.
\u201cWork\u201d shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below).
\u201cDerivative Works\u201d shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof.
\u201cContribution\u201d shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, \u201csubmitted\u201d means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as \u201cNot a Contribution.\u201d
\u201cContributor\u201d shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work.
"},{"location":"license/#2-grant-of-copyright-license","title":"2. Grant of Copyright License","text":"Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form.
"},{"location":"license/#3-grant-of-patent-license","title":"3. Grant of Patent License","text":"Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed.
"},{"location":"license/#4-redistribution","title":"4. Redistribution","text":"You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions:
You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License.
"},{"location":"license/#5-submission-of-contributions","title":"5. Submission of Contributions","text":"Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions.
"},{"location":"license/#6-trademarks","title":"6. Trademarks","text":"This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file.
"},{"location":"license/#7-disclaimer-of-warranty","title":"7. Disclaimer of Warranty","text":"Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an \u201cAS IS\u201d BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License.
"},{"location":"license/#8-limitation-of-liability","title":"8. Limitation of Liability","text":"In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages.
"},{"location":"license/#9-accepting-warranty-or-additional-liability","title":"9. Accepting Warranty or Additional Liability","text":"While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
"},{"location":"license/#appendix-how-to-apply-the-apache-license-to-your-work","title":"APPENDIX: How to apply the Apache License to your work","text":"To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets []
replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same \u201cprinted page\u201d as the copyright notice for easier identification within third-party archives.
Copyright [yyyy] [name of copyright owner]\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n
"},{"location":"user-guide/","title":"The PyScript User Guide","text":"Info
This guide provides technical guidance and exploration of the PyScript platform.
While we endeavour to write clearly, some of the content in this user guide will not be suitable for beginners. We assume you already have Python or web development experience. If you're a beginner start with our beginner's guide.
We welcome constructive feedback.
Our docs have three aims:
Read this user guide in full: it is a short but comprehensive overview of the PyScript platform.
Get involved! Join in the PyScript conversation on our discord server. There you'll find core developers, community contributors and a flourishing forum for those creating projects with PyScript. Should you wish to engage with the development of PyScript, you are welcome to contribute via the project's GitHub organisation.
Finally, the example projects referenced in our docs are all freely available and copiously commented on pyscript.com.
Note
Many of these examples come from contributors in our wonderful community. We love to recognise, share and celebrate the incredible work of folks in the PyScript community. If you believe you have a project that would make a good demonstration, please don't hesitate to get in touch.
"},{"location":"user-guide/architecture/","title":"Architecture, Lifecycle & Interpreters","text":""},{"location":"user-guide/architecture/#core-concepts","title":"Core concepts","text":"PyScript's architecture has three core concepts:
PolyScript is the core of PyScript.
Danger
Unless you are an advanced user, you only need to know that PolyScript exists, and it can be safely ignored.
PolyScript's purpose is to bootstrap the platform and provide all the necessary core capabilities. Setting aside PyScript for a moment, to use just PolyScript requires a <script>
reference to it, along with a further <script>
tag defining how to run your code.
<!doctype html>\n<html>\n<head>\n<!-- this is a way to automatically bootstrap polyscript -->\n<script type=\"module\" src=\"https://cdn.jsdelivr.net/npm/polyscript\"></script>\n</head>\n<body>\n<!--\n Run some Python code with the MicroPython interpreter, but without\n the extra benefits provided by PyScript.\n -->\n<script type=\"micropython\">\nfrom js import document\ndocument.body.textContent = 'polyscript'\n</script>\n</body>\n</html>\n
Warning
PolyScript is not PyScript.
PyScript enhances the available Python interpreters with convenient features, helper functions and easy-to-use yet powerful capabilities.
These enhancements are missing from PolyScript.
PolyScript's capabilities, upon which PyScript is built, can be summarised as:
<script>
tags.XWorker
class and its related reference, xworker
.PolyScript may become important if you encounter problems with PyScript. You should investigate PolyScript if any of the following is true about your problem:
py-*
or mpy-*
) are not triggered.We encourage you to engage and ask questions about PolyScript on our discord server. But in summary, as a user of PyScript you should probably never encounter PolyScript. However, please be aware that specific features of bug fixes my happen in the PolyScript layer in order to then land in PyScript.
"},{"location":"user-guide/architecture/#coincident","title":"Coincident","text":"Danger
Unless you are an advanced user, you only need to know that coincident exists, and it can be safely ignored. As with PolyScript, we include these details only for those interested in the more fundamental aspects of PyScript.
PolyScript uses the coincident library to seamlessly interact with web workers and coordinate interactions between the browser's main thread and such workers.
Any SharedArrayBuffer
issues are the responsibility of coincident and, to some extent, anything related to memory leaks.
In a nutshell, this project is likely responsible for the following modes of failure:
We hope all these scenarios are unlikely to happen within a PyScript project. They are all battle tested and covered with general purpose cross-environment testing before landing in PyScript. But, if you feel something is odd, leaking, or badly broken, please feel free to file an issue in the coincident project. As usual, there is never a silly question, so long as you provide a minimal reproducible example in your bug reports or query.
"},{"location":"user-guide/architecture/#the-stack","title":"The stack","text":"The stack describes how the different building blocks inside a PyScript application relate to each other:
Failure
PyScript is simply Python running in the browser. Please remember:
If the architecture explains how components relate to each other, the lifecycle explains how things unfold. It's important to understand both: it will help you think about your own code and how it sits within PyScript.
Here's how PyScript unfolds through time:
<script>
tag that references PyScript. PyScript is loaded and evaluated as a JavaScript module, meaning it doesn't hold up the loading of the page and is only evaluated when the HTML is fully parsed.<py-config>
or <mpy-config>
tags or the config
attribute of a <script>
, <py-script>
or <mpy-script>
tag).pyscript
module).py:ready
or mpy:ready
events are dispatched, depending which interpreter you've specified (Pyodide or MicroPython respectively).py:done
event is dispatched after every single script referenced from the page has finished.In addition, various \"hooks\" are called at different moments in the lifecycle of PyScript. These can be used by plugin authors to modify or enhance the behaviour of PyScript. The hooks, and how to use them, are explored further in the section on plugins.
Warning
A web page's workers have completely separate environments to the main thread.
It means configuration in the main thread can be different to that for an interpreter running on a worker. In fact, you can use different interpreters and configuration in each context (for instance, MicroPython on the main thread, and Pyodide on a worker).
Think of workers as completely separate sub-processes inside your browser tab.
"},{"location":"user-guide/architecture/#interpreters","title":"Interpreters","text":"Python is an interpreted language, and thus needs an interpreter to work.
PyScript currently supports two versions of the Python interpreter that have been compiled to WASM: Pyodide and MicroPython. You should select which one to use depending on your use case and acceptable trade-offs.
Info
In future, and subject to progress, we hope to make available a third Pythonic option: SPy, a staticially typed version of Python compiled directly to WASM.
Both interpreters make use of emscripten, a compiler toolchain (using LLVM), for emitting WASM assets for the browser. Emscripten also provides APIs so operating-system level features such as a sandboxed file system (not the user's local machine's filesystem), IO (stdin
, stdout
, stderr
etc,) and networking are available within the context of a browser.
Both Pyodide and MicroPython implement the same robust Python \u27fa JavaScript foreign function interface (FFI). This bridges the gap between the browser and Python worlds.
"},{"location":"user-guide/architecture/#pyodide","title":"Pyodide","text":"Pyodide is a version of the standard CPython interpreter, patched to compile to WASM and work in the browser.
It includes many useful features:
Warning
You may encounter an error message from micropip
that explains it can't find a \"pure Python wheel\" for a package. Pyodide's documentation explains what to do in this situation.
Briefly, some packages with C extensions have versions compiled for WASM and these can be installed with micropip
. Packages containing C extensions that are not compiled for WASM cause the \"pure Python wheel\" error.
There are plans afoot to make WASM a target in PyPI so packages with C extensions are automatically compiled to WASM.
"},{"location":"user-guide/architecture/#micropython","title":"MicroPython","text":"MicroPython is a lean and efficient implementation of the Python 3 programming language that includes a small subset of the Python standard library and is optimised to run on microcontrollers and in constrained environments (like the browser).
Everything needed to view a web page in a browser needs to be delivered over the network. The smaller the asset to be delivered can be, the better. MicroPython, when compressed for delivery to the browser, is only around 170k in size - smaller than many images found on the web.
This makes MicroPython particularly suited to browsers running in a more constrained environment such as on a mobile or tablet based device. Browsing with these devices often uses (slower) mobile internet connections. Furthermore, because MicroPython is lean and efficient it still performs exceptionally well on these relatively underpowered devices.
Thanks to collaboration between the MicroPython, Pyodide and PyScript projects, there is a foreign function interface for MicroPython. The MicroPython FFI deliberately copies the API of the FFI originally written for Pyodide - meaning it is relatively easy to migrate between the two supported interpreters via the pyscript.ffi
namespace.
The browser tab in which your PyScript based web page is displayed is a very secure sandboxed computing environment for running your Python code.
This is also the case for web workers running Python. Despite being associated with a single web page, workers are completely separate from each other (except for some very limited and clearly defined means of interacting, which PyScript looks after for you).
We need to tell PyScript how we want such Python environments to be configured. This works in the same way for both the main thread and for web workers. Such configuration ensures we get the expected resources ready before our Python code is evaluated (resources such as arbitrary data files and third party Python packages).
"},{"location":"user-guide/configuration/#toml-or-json","title":"TOML or JSON","text":"Configuration can be expressed in two formats:
Since PyScript is the marriage of Python and the web, and we respect the traditions of both technical cultures, we support both formats.
However, because JSON is built into all browsers by default and TOML requires an additional download of a specialist parser before PyScript can work, the use of JSON is more efficient from a performance point of view.
The following two configurations are equivalent, and simply tell PyScript to ensure the packages arrr and numberwang are installed from PyPI (the Python Packaging Index):
Configuration via TOML.packages = [\"arrr\", \"numberwang\" ]\n
Configuration via JSON.{\n\"packages\": [\"arrr\", \"numberwang\"]\n}\n
"},{"location":"user-guide/configuration/#file-or-inline","title":"File or inline","text":"The recommended way to write configuration is via a separate file and then reference it from the tag used to specify the Python code:
Reference a configuration file<script type=\"py\" src=\"main.py\" config=\"pyscript.toml\"></script>\n
If you use JSON, you can make it the value of the config
attribute:
<script type=\"mpy\" src=\"main.py\" config='{\"packages\":[\"arrr\", \"numberwang\"]}'></script>\n
For historical and convenience reasons we still support the inline specification of configuration information via a single <py-config>
or <mpy-config>
tag in your HTML document:
<py-config>\n{\n \"packages\": [\"arrr\", \"numberwang\" ]\n}\n</py-config>\n
Warning
Should you use <py-config>
or <mpy-config>
, there must be only one of these tags on the page per interpreter.
There are five core options (interpreter
, files
, packages
, js_modules
and sync_main_only
) and an experimental flag (experimental_create_proxy
) that can be used in the configuration of PyScript. The user is also free to define arbitrary additional configuration options that plugins or an app may require for their own reasons.
The interpreter
option pins the Python interpreter to the version of the specified value. This is useful for testing (does my code work on a specific version of Pyodide?), or to ensure the precise combination of PyScript version and interpreter version are pinned to known values.
The value of the interpreter
option should be a valid version number for the Python interpreter you are configuring, or a fully qualified URL to a custom version of the interpreter.
The following two examples are equivalent:
Specify the interpreter version in TOML.interpreter = \"0.23.4\"\n
Specify the interpreter version in JSON.{\n\"interpreter\": \"0.23.4\"\n}\n
The following JSON fragment uses a fully qualified URL to point to the same version of Pyodide as specified in the previous examples:
Specify the interpreter via a fully qualified URL.{\n\"interpreter\": \"https://cdn.jsdelivr.net/pyodide/v0.23.4/full/pyodide.mjs\"\n}\n
"},{"location":"user-guide/configuration/#files","title":"Files","text":"The files
option fetches arbitrary content from URLs onto the filesystem available to Python, and emulated by the browser. Just map a valid URL to a destination filesystem path.
The following JSON and TOML are equivalent:
Fetch files onto the filesystem with JSON.{\n\"files\": {\n\"https://example.com/data.csv\": \"./data.csv\",\n\"/code.py\": \"./subdir/code.py\"\n}\n}\n
Fetch files onto the filesystem with TOML.[files]\n\"https://example.com/data.csv\" = \"./data.csv\"\n\"/code.py\" = \"./subdir/code.py\"\n
If you make the target an empty string, the final \"filename\" part of the source URL becomes the destination filename, in the root of the filesystem, to which the content is copied. As a result, the data.csv
entry from the previous examples could be equivalently re-written as:
{\n\"files\": {\n\"https://example.com/data.csv\": \"\",\n... etc ...\n}\n}\n
TOML implied filename in the root directory.[files]\n\"https://example.com/data.csv\" = \"\"\n... etc ...\n
If the source part of the configuration is either a .zip
or .tar.gz
file and its destination is a folder path followed by a star (e.g. /*
or ./dest/*
), then PyScript will extract the referenced archive automatically into the target directory in the browser's built in file system.
Warning
PyScript expects all file destinations to be unique.
If there is a duplication PyScript will raise an exception to help you find the problem.
Tip
For most people, most of the time, the simple URL to filename mapping, described above, will be sufficient.
Yet certain situations may require more flexibility. In which case, read on.
Sometimes many resources are needed to be fetched from a single location and copied into the same directory on the file system. To aid readability and reduce repetition, the files
option comes with a mini templating language that allows reusable placeholders to be defined between curly brackets ({
and }
). When these placeholders are encountered in the files
configuration, their name is replaced with their associated value.
Attention
Valid placeholder names are always enclosed between curly brackets ({
and }
), like this: {FROM}
, {TO}
and {DATA SOURCE}
(capitalized names help identify placeholders when reading code ~ although this isn't strictly necessary).
Any number of placeholders can be defined and used anywhere within URLs and paths that map source to destination.
The following JSON and TOML are equivalent:
Using the template language in JSON.{\n\"files\": {\n\"{DOMAIN}\": \"https://my-server.com\",\n\"{PATH}\": \"a/path\",\n\"{VERSION}\": \"1.2.3\",\n\"{FROM}\": \"{DOMAIN}/{PATH}/{VERSION}\",\n\"{TO}\": \"./my_module\",\n\"{FROM}/__init__.py\": \"{TO}/__init__.py\",\n\"{FROM}/foo.py\": \"{TO}/foo.py\",\n\"{FROM}/bar.py\": \"{TO}/bar.py\",\n\"{FROM}/baz.py\": \"{TO}/baz.py\",\n}\n}\n
Using the template language in TOML.[files]\n\"{DOMAIN}\" = \"https://my-server.com\"\n\"{PATH}\" = \"a/path\"\n\"{VERSION}\" = \"1.2.3\"\n\"{FROM}\" = \"{DOMAIN}/{PATH}/{VERSION}\"\n\"{TO}\" = \"./my_module\"\n\"{FROM}/__init__.py\" = \"{TO}/__init__.py\"\n\"{FROM}/foo.py\" = \"{TO}/foo.py\"\n\"{FROM}/bar.py\" = \"{TO}/bar.py\"\n\"{FROM}/baz.py\" = \"{TO}/baz.py\"\n
The {DOMAIN}
, {PATH}
, and {VERSION}
placeholders are used to create a further {FROM}
placeholder. The {TO}
placeholder is also defined to point to a common sub-directory on the file system. The final four entries use {FROM}
and {TO}
to copy over four files (__init__.py
, foo.py
, bar.py
and baz.py
) from the same source to a common destination directory.
For convenience, if the destination is just a directory (it ends with /
) then PyScript automatically uses the filename part of the source URL as the filename in the destination directory.
For example, the end of the previous config file could be:
\"{TO}\" = \"./my_module/\"\n\"{FROM}/__init__.py\" = \"{TO}\"\n\"{FROM}/foo.py\" = \"{TO}\"\n\"{FROM}/bar.py\" = \"{TO}\"\n\"{FROM}/baz.py\" = \"{TO}\"\n
"},{"location":"user-guide/configuration/#packages","title":"Packages","text":"The packages
option lists Python packages to be installed onto the Python path.
Info
Pyodide uses a utility called micropip
to install packages from PyPI.
Because micropip
is a Pyodide-only feature, and MicroPython doesn't support code packaged on PyPI, the packages
option only works with packages hosted on PyPI when using Pyodide.
MicroPython's equivalent utility, mip
, uses a separate repository of available packages called micropython-lib
. When you use the packages
option with MicroPython, it is this repository (not PyPI) that is used to find available packages. Many of the packages in micropython-lib
are for microcontroller based activities and may not work with the web assembly port of MicroPython.
If you need pure Python modules for MicroPython, you have two further options:
The following two examples are equivalent:
A packages list in TOML.packages = [\"arrr\", \"numberwang\", \"snowballstemmer>=2.2.0\" ]\n
A packages list in JSON.{\n\"packages\": [\"arrr\", \"numberwang\", \"snowballstemmer>=2.2.0\" ]\n}\n
When using Pyodide, the names in the list of packages
can be any of the following valid forms:
\"snowballstemmer\"
\"snowballstemmer>=2.2.0\"
\"https://.../package.whl\"
\"emfs://.../package.whl\"
It's easy to import and use JavaScript modules in your Python code. This section of the docs examines the configuration needed to make this work. How to make use of JavaScript is dealt with elsewhere.
We need to tell PyScript about the JavaScript modules you want to use. This is the purpose of the js_modules
related configuration fields.
There are two fields:
js_modules.main
defines JavaScript modules loaded in the context of the main thread of the browser. Helpfully, it is also possible to interact with such modules from the context of workers. Sometimes such modules also need CSS files to work, and these can also be specified.js_modules.worker
defines JavaScript modules loaded into the context of the web worker. Such modules must not expect document
or window
references (if this is the case, you must load them via js_modules.main
and use them from the worker). However, if the JavaScript module could work without such references, then performance is better if defined on a worker. Because CSS is meaningless in the context of a worker, it is not possible to specify such files in a worker context.Once specified, your JavaScript modules will be available under the pyscript.js_modules.*
namespace.
To specify such modules, simply provide a list of source/module name pairs.
For example, to use the excellent Leaflet JavaScript module for creating interactive maps you'd add the following lines:
JavaScript main thread modules defined in TOML.[js_modules.main]\n\"https://cdn.jsdelivr.net/npm/leaflet@1.9.4/dist/leaflet-src.esm.js\" = \"leaflet\"\n\"https://cdn.jsdelivr.net/npm/leaflet@1.9.4/dist/leaflet.css\" = \"leaflet\" # CSS\n
JavaScript main thread modules defined in JSON.{\n\"js_modules\": {\n\"main\": {\n\"https://cdn.jsdelivr.net/npm/leaflet@1.9.4/dist/leaflet-src.esm.js\": \"leaflet\",\n\"https://cdn.jsdelivr.net/npm/leaflet@1.9.4/dist/leaflet.css\": \"leaflet\"\n}\n}\n}\n
Info
Notice how the second line references the required CSS needed for the JavaScript module to work correctly.
The CSS file MUST target the very same name as the JavaScript module to which it is related.
Warning
Since the Leaflet module expects to manipulate the DOM and have access to document
and window
references, it must only be added via the js_modules.main
setting (as shown) and cannot be added in a worker context.
At this point Python code running on either the main thread or in a worker will have access to the JavaScript module like this:
Making use of a JavaScript module from within Python.from pyscript.js_modules import leaflet as L\nmap = L.map(\"map\")\n# etc....\n
Some JavaScript modules (such as html-escaper) don't require access to the DOM and, for efficiency reasons, can be included in the worker context:
A JavaScript worker module defined in TOML.[js_modules.worker]\n\"https://cdn.jsdelivr.net/npm/html-escaper\" = \"html_escaper\"\n
A JavaScript worker module defined in JSON.{\n\"js_modules\": {\n\"worker\": {\n\"https://cdn.jsdelivr.net/npm/html-escaper\": \"html_escaper\"\n}\n}\n}\n
However, from pyscript.js_modules import html_escaper
would then only work within the context of Python code running on a worker.
Sometimes you just want to start an expensive computation on a web worker without the need for the worker to interact with the main thread. You're simply awaiting the result of a method exposed from a worker.
This has the advantage of not requiring the use of SharedArrayBuffer
and associated CORS related header configuration.
If the sync_main_only
flag is set, then interactions between the main thread and workers are limited to one way calls from the main thread to methods exposed by the workers.
sync_main_only = true\n
Setting the sync_main_only flag in JSON.{\n\"sync_main_only\": true\n}\n
If sync_main_only
is set, the following caveats apply:
pyscript.sync
methods are exposed, and they can only be awaited from the main thread.await
main thread references one after the other, so developer experience is degraded when one needs to interact with the main thread.Knowing when to use the pyscript.ffi.create_proxy
method when using Pyodide can be confusing at the best of times and full of technical \"magic\".
This experimental flag, when set to \"auto\"
will cause PyScript to try to automatically handle such situations, and should \"just work\".
experimental_create_proxy = \"auto\"\n
Using the experimental_create_proxy flag in JSON.{\n\"experimental_create_proxy\": \"auto\"\n}\n
Warning
This feature is experimental and only needs to be used with Pyodide.
Should you encounter problems (such as problematic memory leaks) when using this flag with Pyodide, please don't hesitate to raise an issue with a reproducable example, and we'll investigate.
"},{"location":"user-guide/configuration/#custom","title":"Custom","text":"Sometimes plugins or apps need bespoke configuration options.
So long as you don't cause a name collision with the built-in option names then you are free to use any valid data structure that works with both TOML and JSON to express your configuration needs.
Access the current configuration via pyscript.config
, a Python dict
representing the configuration:
from pyscript import config\n# It's just a dict.\nprint(config.get(\"files\"))\n
Note
Changing the config
dictionary at runtime doesn't change the actual configuration.
The DOM (document object model) is a tree like data structure representing the web page displayed by the browser. PyScript interacts with the DOM to change the user interface and react to things happening in the browser.
There are currently two ways to interact with the DOM:
globalThis
or document
objects.pydom
module that acts as a Pythonic wrapper around the FFI and comes as standard with PyScript.The foreign function interface (FFI) gives Python access to all the standard web capabilities and features, such as the browser's built-in web APIs.
This is available via the pyscript.window
module which is a proxy for the main thread's globalThis
object, or pyscript.document
which is a proxy for the website's document
object in JavaScript:
from pyscript import window, document\nmy_element = document.querySelector(\"#my-id\")\nmy_element.innerText = window.location.hostname\n
The FFI creates proxy objects in Python linked to actual objects in JavaScript.
The proxy objects in your Python code look and behave like Python objects but have related JavaScript objects associated with them. It means the API defined in JavaScript remains the same in Python, so any browser based JavaScript APIs or third party JavaScript libraries that expose objects in the web page's globalThis
, will have exactly the same API in Python as in JavaScript.
The FFI automatically transforms Python and JavaScript objects into the equivalent in the other language. For example, Python's boolean True
and False
will become JavaScript's true
and false
, while a JavaScript array of strings and integers, [\"hello\", 1, 2, 3]
becomes a Python list of the equivalent values: [\"hello\", 1, 2, 3]
.
Info
Instantiating classes into objects is an interesting special case that the FFI expects you to handle.
If you wish to instantiate a JavaScript class in your Python code, you need to call the class's new
method:
from pyscript import window\nmy_obj = window.MyJavaScriptClass.new(\"some value\")\n
The underlying reason for this is simply JavaScript and Python do instantiation very differently. By explicitly calling the JavaScript class's new
method PyScript both signals and honours this difference.
More technical information about instantiating JavaScript classes can be found in the FAQ
Should you require lower level API access to FFI features, you can find such builtin functions under the pyscript.ffi
namespace in both Pyodide and MicroPython. The available functions are described in our section on the builtin API.
Advanced users may wish to explore the technical details of the FFI.
"},{"location":"user-guide/dom/#pyscriptweb","title":"pyscript.web
","text":"Warning
The pyscript.web
module is currently a work in progress.
We welcome feedback and suggestions.
The pyscript.web
module is an idiomatically Pythonic API for interacting with the DOM. It wraps the FFI in a way that is more familiar to Python developers and works natively with the Python language. Technical documentation for this module can be found in the API section.
There are three core concepts to remember:
find
API uses exactly the same queries as those used by native browser methods like qurerySelector
or querySelectorAll
.pyscript.web
namespace to create and organise new elements on the web page.find
queries and are also used for the children of an element.You have several options for accessing the content of the page, and these are all found in the pyscript.web.page
object. The html
, head
and body
attributes reference the page's top-level html, head and body. As a convenience the page
's title
attribute can be used to get and set the web page's title (usually shown in the browser's tab). The append
method is a shortcut for adding content to the page's body
. Whereas, the find
method is used to return collections of elements matching a CSS query. You may also shortcut find
via a CSS query in square brackets. Finally, all elements have a find
method that searches within their children for elements matching your CSS query.
from pyscript.web import page\n# Print all the child elements of the document's head.\nprint(page.head.children)\n# Find all the paragraphs in the DOM.\nparagraphs = page.find(\"p\")\n# Or use square brackets.\nparagraphs = page[\"p\"]\n
The object returned from a query, or used as a reference to an element's children is iterable:
from pyscript.web import page\n# Get all the paragraphs in the DOM.\nparagraphs = page[\"p\"]\n# Print the inner html of each paragraph.\nfor p in paragraphs:\nprint(p.html)\n
Alternatively, it is also indexable / sliceable:
from pyscript.web import page\n# Get an ElementCollection of all the paragraphs in the DOM\nparagraphs = page[\"p\"]\n# Only the final two paragraphs.\nfor p in paragraphs[-2:]:\nprint(p.html)\n
You have access to all the standard attributes related to HTML elements (for example, the innerHTML
or value
), along with a couple of convenient ways to interact with classes and CSS styles:
classes
- the list of classes associated with the elements.style
- a dictionary like object for interacting with CSS style rules.For example, to continue the example above, paragraphs.innerHTML
will return a list of all the values of the innerHTML
attribute on each contained element. Alternatively, set an attribute for all elements contained in the collection like this: paragraphs.style[\"background-color\"] = \"blue\"
.
It's possible to create new elements to add to the page:
from pyscript.web import page, div, select, option, button, span, br \npage.append(\ndiv(\ndiv(\"Hello!\", classes=\"a-css-class\", id=\"hello\"),\nselect(\noption(\"apple\", value=1),\noption(\"pear\", value=2),\noption(\"orange\", value=3),\n),\ndiv(\nbutton(span(\"Hello! \"), span(\"World!\"), id=\"my-button\"),\nbr(),\nbutton(\"Click me!\"),\nclasses=[\"css-class1\", \"css-class2\"],\nstyle={\"background-color\": \"red\"}\n),\ndiv(\nchildren=[\nbutton(\nchildren=[\nspan(\"Hello! \"),\nspan(\"Again!\")\n],\nid=\"another-button\"\n),\nbr(),\nbutton(\"b\"),\n],\nclasses=[\"css-class1\", \"css-class2\"]\n)\n)\n)\n
This example demonstrates a declaritive way to add elements to the body of the page. Notice how the first (unnamed) arguments to an element are its children. The named arguments (such as id
, classes
and style
) refer to attributes of the underlying HTML element. If you'd rather be explicit about the children of an element, you can always pass in a list of such elements as the named children
argument (you see this in the final div
in the example above).
Of course, you can achieve similar results in an imperative style of programming:
from pyscript.web import page, div, p \nmy_div = div()\nmy_div.style[\"background-color\"] = \"red\"\nmy_div.classes.append(\"a-css-class\")\nmy_p = p()\nmy_p.content = \"This is a paragraph.\"\nmy_div.append(my_p)\n# etc...\n
It's also important to note that the pyscript.when
decorator understands element references from pyscript.web
:
from pyscript import when\nfrom pyscript.web import page \nbtn = page[\"#my-button\"]\n@when(\"click\", btn)\ndef my_button_click_handler(event):\nprint(\"The button has been clicked!\")\n
Should you wish direct access to the proxy object representing the underlying HTML element, each Python element has a _dom_element
property for this purpose.
Once again, the technical details of these classes are described in the built-in API documentation.
"},{"location":"user-guide/dom/#working-with-javascript","title":"Working with JavaScript","text":"There are three ways in which JavaScript can get into a web page.
window
object in the web page because the code was referenced as the source of a script
tag in your HTML (the very old school way to do this).Sadly, this being the messy world of the web, methods 1 and 2 are still quite common, and so you need to know about them so you're able to discern and work around them. There's nothing WE can do about this situation, but we can suggest \"best practice\" ways to work around each situation.
Remember, as mentioned elsewhere in our documentation, the standard way to get JavaScript modules into your PyScript Python context is to link a source standard JavaScript module to a destination name:
Reference a JavaScript module in the configuration.[js_modules.main]\n\"https://cdn.jsdelivr.net/npm/leaflet@1.9.4/dist/leaflet-src.esm.js\" = \"leaflet\"\n
Then, reference the module via the destination name in your Python code, by importing it from the pyscript.js_modules
namespace:
from pyscript.js_modules import leaflet as L\nmap = L.map(\"map\")\n# etc....\n
We'll deal with each of the potential JavaScript related situations in turn:
"},{"location":"user-guide/dom/#javascript-as-a-global-reference","title":"JavaScript as a global reference","text":"In this situation, you have some JavaScript code that just globally defines \"stuff\" in the context of your web page via a script
tag. Your HTML will contain something like this:
<!doctype html>\n<!--\nThis JS utility escapes and unescapes HTML chars. It adds an \"html\" object to\nthe global context.\n-->\n<script src=\"https://cdn.jsdelivr.net/npm/html-escaper@3.0.3/index.js\"></script>\n<!--\nVanilla JS just to check the expected object is in the global context of the\nweb page.\n-->\n<script>\nconsole.log(html);\n</script>\n
When you find yourself in this situation, simply use the window
object in your Python code (found in the pyscript
namespace) to interact with the resulting JavaScript objects:
from pyscript import window, document\n# The window object is the global context of your web page.\nhtml = window.html\n# Just use the object \"as usual\"...\n# e.g. show escaped HTML in the body: <>\ndocument.body.append(html.escape(\"<>\"))\n
You can find an example of this technique here:
https://pyscript.com/@agiammarchi/floral-glade/v1
"},{"location":"user-guide/dom/#javascript-as-a-non-standard-umd-module","title":"JavaScript as a non-standard UMD module","text":"Sadly, these sorts of non-standard JavaScript modules are still quite prevalent. But the good news is there are strategies you can use to help you get them to work properly.
The non-standard UMD approach tries to check for export
and module
fields in the JavaScript module and, if it doesn\u2019t find them, falls back to treating the module in the same way as a global reference described above.
If you find you have a UMD JavaScript module, there are services online to automagically convert it to the modern and standards compliant way to d o JavaScript modules. A common (and usually reliable) service is provided by https://esm.run/your-module-name, a service that provides an out of the box way to consume the module in the correct and standard manner:
Use esm.run to automatically convert a non-standard UMD module<!doctype html>\n<script type=\"module\">\n// this utility escapes and unescape HTML chars\nimport { escape, unescape } from \"https://esm.run/html-escaper\";\n// esm.run returns a module ^^^^^^^^^^^^^^^^^^^^^^^^^^^^\nconsole.log(escape(\"<>\"));\n// log: \"<>\"\n</script>\n
If a similar test works for the module you want to use, use the esm.run CDN service within the py
or mpy
configuration file as explained at the start of this section on JavaScript (i.e. you'll use it via the pyscript.js_modules
namespace).
If this doesn't work, assume the module is not updated nor migrated to a state that can be automatically translated by services like esm.run. You could try an alternative (more modern) JavaScript module to achieve you ends or (if it really must be this module), you can wrap it in a new JavaScript module that conforms to the modern standards.
The following four files demonstrate this approach:
index.html - still grab the script so it appears as a global reference.<!doctype html>\n...\n<!-- land the utility still globally as generic script -->\n<script src=\"https://cdn.jsdelivr.net/npm/html-escaper@3.0.3/index.js\"></script>\n...\n
wrapper.js - this grabs the JavaScript functionality from the global context and wraps it (exports it) in the modern standards compliant manner.// get all utilities needed from the global.\nconst { escape, unescape } = globalThis.html;\n// export utilities like a standards compliant module would do.\nexport { escape, unescape };\n
pyscript.toml - configure your JS modules as before, but use your wrapper instead of the original module.[js_modules.main]\n# will simulate a standard JS module\n\"./wrapper.js\" = \"html_escaper\"\n
main.py - just import the module as usual and make use of it.from pyscript import document\n# import the module either via\nfrom pyscript.js_modules import html_escaper\n# or via\nfrom pyscript.js_modules.html_escaper import escape, unescape\n# show on body: <>\ndocument.body.append(html.escape(\"<>\"))\n
You can see this approach in action here:
https://pyscript.com/@agiammarchi/floral-glade/v2
"},{"location":"user-guide/dom/#a-standard-javascript-module","title":"A standard JavaScript module","text":"This is both the easiest and best way to import any standard JS module into Python.
You don't need to reference the script in your HTML, just define how the source JavaScript module maps into the pyscript.js_modules
namespace in your configuration file, as explained above.
That's it!
Here is an example project that uses this approach:
https://pyscript.com/@agiammarchi/floral-glade/v3
"},{"location":"user-guide/dom/#my-own-javascript-code","title":"My own JavaScript code","text":"If you have your own JavaScript work, just remember to write it as a standard JavaScript module. Put simply, ensure you export
the things you need to. For instance, in the following fragment of JavaScript, the two functions are exported from the module:
/*\nSome simple JavaScript functions for example purposes.\n*/\nexport function hello(name) {\nreturn \"Hello \" + name;\n}\nexport function fibonacci(n) {\nif (n == 1) return 0;\nif (n == 2) return 1;\nreturn fibonacci(n - 1) + fibonacci(n - 2);\n}\n
Next, just reference this module in the usual way in your TOML or JSON configuration file:
pyscript.toml - references the code.js module so it will appear as the code module in the pyscript.js_modules namespace.[js_modules.main]\n\"code.js\" = \"code\"\n
In your HTML, reference your Python script with this configuration file:
Reference the expected configuration file.<script type=\"py\" src=\"./main.py\" config=\"./pyscript.toml\" terminal></script>\n
Finally, just use your JavaScript module\u2019s exported functions inside PyScript:
Just call your bespoke JavaScript code from Python.from pyscript.js_modules import code\n# Just use the JS code from Python \"as usual\".\ngreeting = code.hello(\"Chris\")\nprint(greeting)\nresult = code.fibonacci(12)\nprint(result)\n
You can see this in action in the following example project:
https://pyscript.com/@ntoll/howto-javascript/latest
"},{"location":"user-guide/editor/","title":"Python editor","text":"The PyEditor is a core plugin.
Warning
Work on the Python editor is in its early stages. We have made it available in this version of PyScript to give the community an opportunity to play, experiment and provide feedback.
Future versions of PyScript will include a more refined, robust and perhaps differently behaving version of the Python editor.
If you specify the type of a <script>
tag as either py-editor
(for Pyodide) or mpy-editor
(for MicroPython), the plugin creates a visual code editor, with code highlighting and a \"run\" button to execute the editable code contained therein in a non-blocking worker.
Info
Once clicked, the \"run\" button will show a spinner until the code is executed. This may not be visible if the code evaluation completed quickly.
The interpreter is not loaded onto the page until the run button is clicked. By default each editor has its own independent instance of the specified interpreter:
Two editors, one with Pyodide, the other with MicroPython.<script type=\"py-editor\">\nimport sys\nprint(sys.version)\n</script>\n<script type=\"mpy-editor\">\nimport sys\nprint(sys.version)\na = 42\nprint(a)\n</script>\n
However, different editors can share the same interpreter if they share the same env
attribute value.
<script type=\"mpy-editor\" env=\"shared\">\nif not 'a' in globals():\na = 1\nelse:\na += 1\nprint(a)\n</script>\n<script type=\"mpy-editor\" env=\"shared\">\n# doubled a\nprint(a * 2)\n</script>\n
The outcome of these code fragments should look something like this:
Info
Notice that the interpreter type, and optional environment name is shown at the top right above the Python editor.
Hovering over the Python editor reveals the \"run\" button.
"},{"location":"user-guide/editor/#setup","title":"Setup","text":"Sometimes you need to create a pre-baked Pythonic context for a shared environment used by an editor. This need is especially helpful in educational situations where boilerplate code can be run, with just the important salient code available in the editor.
To achieve this end use the setup
attribute within a script
tag. The content of this editor will not be shown, but will bootstrap the referenced environment automatically before any following editor within the same environment is evaluated.
<script type=\"mpy-editor\" env=\"test_env\" setup>\n# This code will not be visible, but will run before the next editor's code is\n# evaluated.\na = 1\n</script>\n<script type=\"mpy-editor\" env=\"test_env\">\n# Without the \"setup\" attribute, this editor is visible. Because it is using\n# the same env as the previous \"setup\" editor, the previous editor's code is\n# always evaluated first.\nprint(a)\n</script>\n
Finally, the target
attribute allows you to specify a node into which the editor will be rendered:
<script type=\"mpy-editor\" target=\"editor\">\nimport sys\nprint(sys.version)\n</script>\n<div id=\"editor\"></div> <!-- will eventually contain the Python editor -->\n
"},{"location":"user-guide/editor/#editor-vs-terminal","title":"Editor VS Terminal","text":"The editor and terminal are commonly used to embed interactive Python code into a website. However, there are differences between the two plugins, of which you should be aware.
The main difference is that a py-editor
or mpy-editor
is an isolated environment (from the rest of PyScript that may be running on the page) and its code always runs in a web worker. We do this to prevent accidental blocking of the main thread that would freeze your browser's user interface.
Because an editor is isolated from regular py or mpy scripts, one should not expect the same behavior regular PyScript elements follow, most notably:
Ctrl-Enter
or Cmd-Enter
, and Shift-Enter
to shortcut the execution of all the code. These shortcuts make no sense in the terminal as each line is evaluated separately.input
) with the editor, whereas these will work if running the terminal via a worker.script.terminal
or __terminal__
in the terminal.Sometimes you need to programatically read, write or execute code in an editor. Once PyScript has started, every py-editor/mpy-editor script tag gets a code
accessor attached to it.
from pyscript import document\n# Grab the editor script reference.\neditor = document.querySelector('#editor')\n# Output the live content of the editor.\nprint(editor.code)\n# Update the live content of the editor.\neditor.code = \"\"\"\na = 1\nb = 2\nprint(a + b)\n\"\"\"\n# Evaluate the live code in the editor.\n# This could be any arbitrary code to evaluate in the editor's Python context.\neditor.process(editor.code)\n
"},{"location":"user-guide/editor/#configuration","title":"Configuration","text":"Unlike <script type=\"py\">
or <py-script>
(and the mpy
equivalents), a PyEditor is not influenced by the presence of <py-config>
elements in the page: it requires an explicit config=\"...\"
attribute.
If a setup
editor is present, that's the only PyEditor that needs a config. Any subsequent related editor will reuse the config parsed and bootstrapped for the setup
editor.
Depending on your operating system, a combination of either Ctrl-Enter
, Cmd-Enter
or Shift-Enter
will execute the code in the editor (no need to move the mouse to click the run button).
Sometimes you just need to override the way the editor runs code.
The editor's handleEvent
can be overridden to achieve this:
<script type=\"mpy-editor\" id=\"foreign\">\nprint(6 * 7)\n</script>\n<script type=\"mpy\">\nfrom pyscript import document\ndef handle_event(event):\n# will log `print(6 * 7)`\nprint(event.code)\n# prevent default execution\nreturn False\n# Grab reference to the editor\nforeign = document.getElementById(\"foreign\")\n# Override handleEvent with your own customisation.\nforeign.handleEvent = handle_event\n</script>\n
This live example shows how the editor can be used to execute code via a USB serial connection to a connected MicroPython microcontroller.
"},{"location":"user-guide/editor/#tab-behavior","title":"Tab behavior","text":"We currently trap the tab
key in a way that reflects what a regular code editor would do: the code is simply indented, rather than focus moving to another element.
We are fully aware of the implications this might have around accessibility so we followed this detailed advice from Codemirror's documentation We have an escape hatch to move focus outside the editor. Press esc
before tab
to move focus to the next focusable element. Otherwise tab
indents code.
The PyEditor is currently under active development and refinement, so features may change (depending on user feedback). For instance, there is currently no way to stop or kill a web worker that has got into difficulty from the editor (hint: refreshing the page will reset things).
"},{"location":"user-guide/features/","title":"Features","text":"All the webPyscript gives you full access to the DOM and all the web APIs implemented by your browser.
Thanks to the foreign function interface (FFI), Python just works with all the browser has to offer, including any third party JavaScript libraries that may be included in the page.
The FFI is bi-directional ~ it also enables JavaScript to access the power of Python.
All of PythonPyScript brings you two Python interpreters:
Because it is just regular CPython, Pyodide puts Python's deep and diverse ecosystem of libraries, frameworks and modules at your disposal. No matter the area of computing endeavour, there's probably a Python library to help. Got a favourite library in Python? Now you can use it in the browser and share your work with just a URL.
MicroPython, because of its small size (170k) and speed, is especially suited to running on more constrained browsers, such as those on mobile or tablet devices. It includes a powerful sub-set of the Python standard library and efficiently exposes the expressiveness of Python to the browser.
Both Python interpreters supported by PyScript implement the same FFI to bridge the gap between the worlds of Python and the browser.
AI and Data science built in Python is famous for its extraordinary usefulness in artificial intelligence and data science. The Pyodide interpreter comes with many of the libraries you need for this sort of work already baked in. Mobile friendly MicroPythonThanks to MicroPython in PyScript, there is a compelling story for Python on mobile.
MicroPython is small and fast enough that your app will start quickly on first load, and almost instantly (due to the cache) on subsequent runs.
Parallel execution Thanks to a browser technology called web workers expensive and blocking computation can run somewhere other than the main application thread controlling the user interface. When such work is done on the main thread, the browser appears frozen; web workers ensure expensive blocking computation happens elsewhere. Think of workers as independent subprocesses in your web page. Rich and powerful pluginsPyScript has a small, efficient yet powerful core called PolyScript. Most of the functionality of PyScript is actually implemented through PolyScript's plugin system.
This approach ensures a clear separation of concerns: PolyScript can focus on being small, efficient and powerful, whereas the PyScript related plugins allow us to Pythonically build upon the solid foundations of PolyScript.
Because there is a plugin system, folks independent of the PyScript core team have a way to create and contribute to a rich ecosystem of plugins whose functionality reflects the unique and diverse needs of PyScript's users.
"},{"location":"user-guide/ffi/","title":"PyScript FFI","text":"The foreign function interface (FFI) gives Python access to JavaScript, and JavaScript access to Python. As a result PyScript is able to access all the standard APIs and capabilities provided by the browser.
We provide a unified pyscript.ffi
because Pyodide's FFI is only partially implemented in MicroPython and there are some fundamental differences. The pyscript.ffi
namespace smooths out such differences into a uniform and consistent API.
Our pyscript.ffi
offers the following utilities:
ffi.to_js(reference)
converts a Python object into its JavaScript counterpart.ffi.create_proxy(def_or_lambda)
proxies a generic Python function into a JavaScript one, without destroying its reference right away.Should you require access to Pyodide or MicroPython's specific version of the FFI you'll find them under the pyodide.ffi
and micropython.ffi
namespaces. Please refer to the documentation for those projects for further information.
In the Pyodide project, this utility converts Python dictionaries into JavaScript Map
objects. Such Map
objects reflect the obj.get(field)
semantics native to Python's way of retrieving a value from a dictionary.
Unfortunately, this default conversion breaks the vast majority of native and third party JavaScript APIs. This is because the convention in idiomatic JavaScript is to use an object for such key/value data structures (not a Map
instance).
A common complaint has been the repeated need to call to_js
with the long winded argument dict_converter=js.Object.fromEntries
. It turns out, most people most of the time simply want to map a Python dict
to a JavaScript object
(not a Map
).
Furthermore, in MicroPython the default Python dict
conversion is to the idiomatic and sensible JavaScript object
, making the need to specify a dictionary converter pointless.
Therefore, if there is no reason to hold a Python reference in a JavaScript context (which is 99% of the time, for common usage of PyScript) then use the pyscript.ffi.to_js
function, on both Pyodide and MicroPython, to always convert a Python dict
to a JavaScript object
.
<!-- works on Pyodide (type py) only -->\n<script type=\"py\">\nfrom pyodide.ffi import to_js\n# default into JS new Map([[\"a\", 1], [\"b\", 2]])\nto_js({\"a\": 1, \"b\": 2})\n</script>\n<!-- works on both Pyodide and MicroPython -->\n<script type=\"py\">\nfrom pyscript.ffi import to_js\n# always default into JS {\"a\": 1, \"b\": 2}\nto_js({\"a\": 1, \"b\": 2})\n</script>\n
Note
It is still possible to specify a different dict_converter
or use Pyodide specific features while converting Python references by simply overriding the explicit field for dict_converter
.
However, we cannot guarantee all fields and features provided by Pyodide will work in the same way on MicroPython.
"},{"location":"user-guide/ffi/#create_proxy","title":"create_proxy","text":"In the Pyodide project, this function ensures that a Python callable associated with an event listener, won't be garbage collected immediately after the function is assigned to the event. Therefore, in Pyodide, if you do not wrap your Python function, it is immediately garbage collected after being associated with an event listener.
This is so common a gotcha (see the FAQ for more on this) that the Pyodide project have already created many work-arounds to address this situation. For example, the create_once_callable
, pyodide.ffi.wrappers.add_event_listener
and pyodide.ffi.set_timeout
are all methods whose goal is to automatically manage the lifetime of the passed in Python callback.
Add to this situation methods connected to the JavaScript Promise
object (.then
and .catch
callbacks that are implicitly handled to guarantee no leaks once executed) and things start to get confusing and overwhelming with many ways to achieve a common end result.
Ultimately, user feedback suggests folks simply want to do something like this, as they write their Python code:
Define a callback without create_proxy.import js\nfrom pyscript import window\ndef callback(msg):\n\"\"\"\n A Python callable that logs a message.\n \"\"\"\nwindow.console.log(msg)\n# Use the callback without having to explicitly create_proxy.\njs.setTimeout(callback, 1000, 'success')\n
Therefore, PyScript provides an experimental configuration flag called experimental_create_proxy = \"auto\"
. When set, you should never have to care about these technical details nor use the create_proxy
method and all the JavaScript callback APIs should just work.
Under the hood, the flag is strictly coupled with the JavaScript garbage collector that will eventually destroy all proxy objects created via the FinalizationRegistry built into the browser.
This flag also won't affect MicroPython because it rarely needs a create_proxy
at all when Python functions are passed to JavaScript event handlers. MicroPython automatically handles this situation. However, there might still be rare and niche cases in MicroPython where such a conversion might be needed.
Hence, PyScript retains the create_proxy
method, even though it does not change much in the MicroPython world, although it might be still needed with the Pyodide runtime is you don't use the experimental_create_proxy = \"auto\"
flag.
At a more fundamental level, MicroPython doesn't provide (yet) a way to explicitly destroy a proxy reference, whereas Pyodide still expects to explicitly invoke proxy.destroy()
when the function is not needed.
Warning
In MicroPython proxies might leak due to the lack of a destroy()
method.
Happily, proxies are usually created explicitly for event listeners or other utilities that won't need to be destroyed in the future. So the lack of a destroy()
method in MicroPython is not a problem in this specific, and most common, situation.
Until we have a destroy()
in MicroPython, we suggest testing the experimental_create_proxy
flag with Pyodide so both runtimes handle possible leaks automatically.
For completeness, the following examples illustrate the differences in behaviour between Pyodide and MicroPython:
A classic Pyodide gotcha VS MicroPython<!-- Throws:\nUncaught Error: This borrowed proxy was automatically destroyed\nat the end of a function call. Try using create_proxy or create_once_callable.\n-->\n<script type=\"py\">\nimport js\njs.setTimeout(lambda x: print(x), 1000, \"fail\");\n</script>\n<!-- logs \"success\" after a second -->\n<script type=\"mpy\">\nimport js\njs.setTimeout(lambda x: print(x), 1000, \"success\");\n</script>\n
To address the difference in Pyodide's behaviour, we can use the experimental flag:
experimental create_proxy<py-config>\n experimental_create_proxy = \"auto\"\n</py-config>\n<!-- logs \"success\" after a second in both Pyodide and MicroPython -->\n<script type=\"py\">\nimport js\njs.setTimeout(lambda x: print(x), 1000, \"success\");\n</script>\n
Alternatively, create_proxy
via the pyscript.ffi
in both interpreters, but only in Pyodide can we then destroy such proxy:
<!-- success in both Pyodide and MicroPython -->\n<script type=\"py\">\nfrom pyscript.ffi import create_proxy\nimport js\ndef log(x):\ntry:\nproxy.destroy()\nexcept:\npass # MicroPython\nprint(x)\nproxy = create_proxy(log)\njs.setTimeout(proxy, 1000, \"success\");\n</script>\n
"},{"location":"user-guide/first-steps/","title":"First steps","text":"It's simple:
That's it!
For the browser to use PyScript, simply add a <script>
tag, whose src
attribute references a CDN url for pyscript.core
, to your HTML document's <head>
. We encourage you to add a reference to optional PyScript related CSS:
<!doctype html>\n<html>\n<head>\n<!-- Recommended meta tags -->\n<meta charset=\"UTF-8\">\n<meta name=\"viewport\" content=\"width=device-width,initial-scale=1.0\">\n<!-- PyScript CSS -->\n<link rel=\"stylesheet\" href=\"https://pyscript.net/releases/2024.9.1/core.css\">\n<!-- This script tag bootstraps PyScript -->\n<script type=\"module\" src=\"https://pyscript.net/releases/2024.9.1/core.js\"></script>\n</head>\n<body>\n<!-- your code goes here... -->\n</body>\n</html>\n
There are two ways to tell PyScript how to find your code.
<script>
tag whose type
attribute is either py
(for Pyodide) or mpy
(for MicroPython). This is the recommended way.<py-script>
(Pyodide) and <mpy-script>
(MicroPython) tags. Historically, <py-script>
used to be the only way to reference your code.These should be inserted into the <body>
of your HTML document.
In both cases either use the src
attribute to reference a Python file containing your code, or inline your code between the opening and closing tags. We recommend you use the src
attribute method, but retain the ability to include code between tags for convenience.
Here's a <script>
tag with a src
attribute containing a URL pointing to a main.py
Python file.
<script type=\"mpy\" src=\"main.py\"></script>\n
...and here's a <py-script>
tag with inline Python code.
<py-script>\nimport sys\nfrom pyscript import display\n\ndisplay(sys.version)\n</py-script>\n
The <script>
and <py-script>
/ <mpy-script>
tags may have the following attributes:
src
- the content of the tag is ignored and the Python code in the referenced file is evaluated instead. This is the recommended way to reference your Python code.config
- your code will only be evaluated after the referenced configuration has been parsed. Since configuration can be JSON or a TOML file, config='{\"packages\":[\"numpy\"]}'
and config=\"./config.json\"
or config=\"./config.toml\"
are all valid.async
- set this flag to \"false\"
so your code won't run within a top level await (the default behaviour).Warning
This behaviour changed in version 2024.8.2.
PyScript now uses a top level await by default.
You used to have to include the async
flag to enable this. Now, instead, use async=\"false\"
to revert the behaviour back to the old default behaviour of synchronous evaluation.
We made this change because many folks were await
-ing functions and missing or not realising the need for the (old) async
attribute. Hence the flip in behaviour.
worker
- a flag to indicate your Python code is to be run on a web worker instead of the \"main thread\" that looks after the user interface.target
- the id or selector of the element where calls to display()
should write their values. terminal
- a traditional terminal is shown on the page. As with conventional Python, print
statements output here. If the worker
flag is set the terminal becomes interactive (e.g. use the input
statement to gather characters typed into the terminal by the user).service-worker
- an optional attribute that allows you to slot in a custom service worker (such as mini-coi.js
) to fix header related problems that limit the use of web workers. This rather technical requirement is fully explained in the section on web workers.Warning
The packages
setting used in the example configuration shown above is for Pyodide using PyPI.
When using MicroPython, and because MicroPython doesn't support code packaged on PyPI, you should use a valid URL to a MicroPython friendly package.
For more information please refer to the packages section of this user guide.
Question
Why do we recommend use of the <script>
tag with a src
attribute?
Within the HTML standard, the <script>
tag is used to embed executable code. Its use case completely aligns with our own, as does its default behaviour.
By referencing a separate Python source file via the src
attribute, your code is just a regular Python file your code editor will understand. Python code embedded within a <script>
tag in an HTML file won't benefit from the advantages code editors bring: syntax highlighting, code analysis, language-based contextual awareness and perhaps even an AI co-pilot.
Both the <py-script>
and <mpy-script>
tags with inline code are web components that are not built into the browser. While they are convenient, there is a performance cost to their use.
Info
The browser's tab displaying the website running PyScript is an isolated computing sandbox. Define the Python environment in which your code will run with configuration options (discussed later in this user guide).
Tip
If you want to run code on both the main thread and in a worker, be explicit and use separate tags.
<script type=\"mpy\" src=\"main.py\"></script> <!-- on the main thread -->\n<script type=\"py\" src=\"worker.py\" worker config=\"pyconfig.toml\"></script> <!-- on the worker -->\n
Notice how different interpreters can be used with different configurations.
"},{"location":"user-guide/offline/","title":"Use PyScript Offline","text":"Sometimes you want to run PyScript applications offline.
Both PyScript core and the interpreter used to run code need to be served with the application itself. The two requirements needed to create an offline version of PyScript are:
You have two choices:
./dist/
folder.In the following instructions, we assume the existence of a folder called pyscript-offline
. All the necessary files needed to use PyScript offline will eventually find their way in there.
In your computer's command line shell, create the pyscript-offline
folder like this:
mkdir -p pyscript-offline\n
Now change into the newly created directory:
cd pyscript-offline\n
"},{"location":"user-guide/offline/#pyscipt-core-from-source","title":"PyScipt core from source","text":"Build PyScript core by cloning the project repository and follow the instructions in our developer guide
Once completed, copy the dist
folder, that has been created by the build step, into your pyscript-offline
folder.
npm
","text":"Ensure you are in the pyscript-offline
folder created earlier.
Create a package.json
file. Even an empty one with just {}
as content will suffice. This is needed to make sure our folder will include the local npm_modules
folder instead of placing assets elsewhere. Our aim is to ensure everything is in the same place locally.
# only if there is no package.json, create one\necho '{}' > ./package.json\n
Assuming you have npm installed on your computer, issue the following command in the pyscript-offline
folder to install the PyScript core package.
# install @pyscript/core\nnpm i @pyscript/core\n
Now the folder should contain a node_module
folder in it, and we can copy the dist
folder found within the @pyscript/core
package wherever we like.
# create a public folder to serve locally\nmkdir -p public\n\n# move @pyscript/core dist into such folder\ncp -R ./node_modules/@pyscript/core/dist ./public/pyscript\n
That's almost it!
"},{"location":"user-guide/offline/#set-up-your-application","title":"Set up your application","text":"Simply create a ./public/index.html
file that loads the local PyScript:
<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n<meta charset=\"UTF-8\">\n<meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">\n<title>PyScript Offline</title>\n<script type=\"module\" src=\"/pyscript/core.js\"></script>\n<link rel=\"stylesheet\" href=\"/pyscript/core.css\">\n</head>\n<body>\n<script type=\"mpy\">\nfrom pyscript import document\ndocument.body.append(\"Hello from PyScript\")\n</script>\n</body>\n</html>\n
Run this project directly (after being sure that index.html
file is saved into the public
folder):
python3 -m http.server -d ./public/\n
If you would like to test worker
features, try instead:
npx mini-coi ./public/\n
"},{"location":"user-guide/offline/#download-a-local-interpreter","title":"Download a local interpreter","text":"PyScript officially supports MicroPython and Pyodide interpreters, so let's see how to get a local copy for each one of them.
"},{"location":"user-guide/offline/#local-micropython","title":"Local MicroPython","text":"Similar to @pyscript/core
, we can also install MicroPython from npm:
npm i @micropython/micropython-webassembly-pyscript\n
Our node_modules
folder should contain a @micropython
one and from there we can move relevant files into our public
folder.
Let's be sure we have a target for that:
# create a folder in our public space\nmkdir -p ./public/micropython\n\n# copy related files into such folder\ncp ./node_modules/@micropython/micropython-webassembly-pyscript/micropython.* ./public/micropython/\n
The folder should contain at least both micropython.mjs
and micropython.wasm
files. These are the files to use locally via a dedicated config.
<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n<meta charset=\"UTF-8\">\n<meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">\n<title>PyScript Offline</title>\n<script type=\"module\" src=\"/pyscript/core.js\"></script>\n<link rel=\"stylesheet\" href=\"/pyscript/core.css\">\n</head>\n<body>\n<mpy-config>\n interpreter = \"/micropython/micropython.mjs\"\n </mpy-config>\n<script type=\"mpy\">\nfrom pyscript import document\ndocument.body.append(\"Hello from PyScript\")\n</script>\n</body>\n</html>\n
"},{"location":"user-guide/offline/#local-pyodide","title":"Local Pyodide","text":"Remember, Pyodide uses micropip
to install third party packages. While the procedure for offline Pyodide is very similar to the one for MicroPython, if we want to use 3rd party packages we also need to have these available locally. We'll start simple and cover such packaging issues at the end.
# locally install the pyodide module\nnpm i pyodide\n\n# create a folder in our public space\nmkdir -p ./public/pyodide\n\n# move all necessary files into that folder\ncp ./node_modules/pyodide/pyodide* ./public/pyodide/\ncp ./node_modules/pyodide/python_stdlib.zip ./public/pyodide/\n
Please note that the pyodide-lock.json
file is needed, so please don't change that cp
operation as all pyodide*
files need to be moved.
At this point, all we need to do is to change the configuration on our HTML page to use pyodide instead:
<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n<meta charset=\"UTF-8\">\n<meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">\n<title>PyScript Offline</title>\n<script type=\"module\" src=\"/pyscript/core.js\"></script>\n<link rel=\"stylesheet\" href=\"/pyscript/core.css\">\n</head>\n<body>\n<py-config>\n interpreter = \"/pyodide/pyodide.mjs\"\n </py-config>\n<script type=\"py\">\nfrom pyscript import document\ndocument.body.append(\"Hello from PyScript\")\n</script>\n</body>\n</html>\n
"},{"location":"user-guide/offline/#wrap-up","title":"Wrap up","text":"That's basically it!
Disconnect from the internet, run the local server, and the page will still show that very same Hello from PyScript
message.
Finally, we need the ability to install Python packages from a local source when using Pyodide.
Put simply, we use the packages bundle from pyodide releases.
Warning
This bundle is more than 200MB!
It contains each package that is required by Pyodide, and Pyodide will only load packages when needed.
Once downloaded and extracted (we're using version 0.26.2
in this example), we can simply copy the files and folders inside the pyodide-0.26.2/pyodide/*
directory into our ./public/pyodide/*
folder.
Feel free to either skip or replace the content, or even directly move the pyodide
folder inside our ./public/
one.
Now use any package available in via the Pyodide bundle.
For example:
<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n<meta charset=\"UTF-8\">\n<meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">\n<title>PyScript Offline</title>\n<script type=\"module\" src=\"/pyscript/core.js\"></script>\n<link rel=\"stylesheet\" href=\"/pyscript/core.css\">\n</head>\n<body>\n<py-config>\n interpreter = \"/pyodide/pyodide.mjs\"\n packages = [\"pandas\"]\n </py-config>\n<script type=\"py\">\nimport pandas as pd\nx = pd.Series([1,2,3,4,5,6,7,8,9,10])\nfrom pyscript import document\ndocument.body.append(str([i**2 for i in x]))\n</script>\n</body>\n</html>\n
We should now be able to read [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
on the page even if we disconnect from the Internet.
That's it!
"},{"location":"user-guide/plugins/","title":"Plugins","text":"PyScript offers a plugin API so anyone can extend its functionality and share their modifications.
PyScript only supports plugins written in Javascript (although causing the evaluation of bespoke Python code can be a part of such plugins). The plugin's JavaScript code should be included on the web page via a <script type=\"module\">
tag before PyScript is included in the web page.
The PyScript plugin API defines hooks that intercept named events in the lifecycle of a PyScript application, so you can modify how the platform behaves. The example at the bottom of this page demonstrates how this is done in code.
"},{"location":"user-guide/plugins/#lifecycle-events","title":"Lifecycle Events","text":"PyScript emits events that capture the beginning or the end of specific stages in the application's life. No matter if code is running in the main thread or on a web worker, the exact same sequence of steps takes place:
script
or tag, and the associated Python interpreter is ready to work. A JavaScript callback can be used to instrument the interpreter before anything else happens.script
or other PyScript related tags is evaluated.PyScript's interpreters can run their code either synchronously or asynchronously (note, the default is asynchronously). No matter, the very same sequence is guaranteed to run in order in both cases, the only difference being the naming convention used to reference synchronous or asynchronous lifecycle hooks.
"},{"location":"user-guide/plugins/#hooks","title":"Hooks","text":"Hooks are used to tell PyScript that your code wants to subscribe to specific lifecycle events. When such events happen, your code will be called by PyScript.
The available hooks depend upon where your code is running: on the browser's (blocking) main thread or on a (non-blocking) web worker. These are defined via the hooks.main
and hooks.worker
namespaces in JavaScript.
Callbacks registered via hooks on the main thread will usually receive a wrapper of the interpreter with its unique-to-that-interpreter utilities, along with a reference to the element on the page from where the code was derived.
Please refer to the documentation for the interpreter you're using (Pyodide or MicroPython) to learn about its implementation details and the potential capabilities made available via the wrapper.
Callbacks whose purpose is simply to run raw contextual Python code, don't receive interpreter or element arguments.
This table lists all possible, yet optional, hooks a plugin can register on the main thread:
name example behavior onReadyonReady(wrap:Wrap, el:Element) {}
If defined, this hook is invoked before any other to signal that the interpreter is ready and code is going to be evaluated. This hook is in charge of eventually running Pythonic content in any way it is defined to do so. onBeforeRun onBeforeRun(wrap:Wrap, el:Element) {}
If defined, it is invoked before to signal that an element's code is going to be evaluated. onBeforeRunAsync onBeforeRunAsync(wrap:Wrap, el:Element) {}
Same as onBeforeRun
, except for scripts that require async
behaviour. codeBeforeRun codeBeforeRun: () => 'print(\"before\")'
If defined, evaluate some Python code immediately before the element's code is evaluated. codeBeforeRunAsync codeBeforeRunAsync: () => 'print(\"before\")'
Same as codeBeforeRun,
except for scripts that require async
behaviour. codeAfterRun codeAfterRun: () => 'print(\"after\")'
If defined, evaluate come Python code immediately after the element's code has finished executing. codeAfterRunAsync codeAfterRunAsync: () => 'print(\"after\")'
Same as codeAfterRun
, except for scripts that require async
behaviour. onAfterRun onAfterRun(wrap:Wrap, el:Element) {}
If defined, invoked immediately after the element's code has been executed. onAfterRunAsync onAfterRunAsync(wrap:Wrap, el:Element) {}
Same as onAfterRun
, except for scripts that require async
behaviour. onWorker onWorker(wrap = null, xworker) {}
If defined, whenever a script or tag with a worker
attribute is processed, this hook is triggered on the main thread. This allows possible xworker
features to be exposed before the code is evaluated on the web worker. The wrap
reference is usually null
unless an explicit XWorker
call has been initialized manually and there is an interpreter on the main thread (very advanced use case). Please note, this is the only hook that doesn't exist in the worker counter list of hooks."},{"location":"user-guide/plugins/#worker-hooks","title":"Worker Hooks","text":"When it comes to hooks on a web worker, callbacks cannot use any JavaScript outer scope references and must be completely self contained. This is because callbacks must be serializable in order to work on web workers since they are actually communicated as strings via a postMessage to the worker's isolated environment.
For example, this will work because all references are contained within the registered function:
import { hooks } from \"https://pyscript.net/releases/2024.9.1/core.js\";\nhooks.worker.onReady.add(() => {\n// NOT suggested, just an example!\n// This code simply defines a global `i` reference if it doesn't exist.\nif (!('i' in globalThis))\nglobalThis.i = 0;\nconsole.log(++i);\n});\n
However, due to the outer reference to the variable i
, this will fail:
import { hooks } from \"https://pyscript.net/releases/2024.9.1/core.js\";\n// NO NO NO NO NO! \u2620\ufe0f\nlet i = 0;\nhooks.worker.onReady.add(() => {\n// The `i` in the outer-scope will cause an error if\n// this code executes in the worker because only the\n// body of this function gets stringified and re-evaluated\nconsole.log(++i);\n});\n
As the worker won't have an element
related to it, since workers can be created procedurally, the second argument won't be a reference to an element
but a reference to the related xworker
object that is driving and coordinating things.
The list of possible yet optional hooks a custom plugin can use with a web worker is exactly the same as for the main thread except for the absence of onWorker
and the replacement of the second element
argument with that of an xworker
.
Here's a contrived example, written in JavaScript, that should be added to the web page via a <script type=\"module\">
tag before PyScript is included in the page.
// import the hooks from PyScript first...\nimport { hooks } from \"https://pyscript.net/releases/2024.9.1/core.js\";\n// The `hooks.main` attribute defines plugins that run on the main thread.\nhooks.main.onReady.add((wrap, element) => {\nconsole.log(\"main\", \"onReady\");\nif (location.search === '?debug') {\nconsole.debug(\"main\", \"wrap\", wrap);\nconsole.debug(\"main\", \"element\", element);\n}\n});\nhooks.main.onBeforeRun.add(() => {\nconsole.log(\"main\", \"onBeforeRun\");\n});\nhooks.main.codeBeforeRun.add('print(\"main\", \"codeBeforeRun\")');\nhooks.main.codeAfterRun.add('print(\"main\", \"codeAfterRun\")');\nhooks.main.onAfterRun.add(() => {\nconsole.log(\"main\", \"onAfterRun\");\n});\n// The `hooks.worker` attribute defines plugins that run on workers.\nhooks.worker.onReady.add((wrap, xworker) => {\nconsole.log(\"worker\", \"onReady\");\nif (location.search === '?debug') {\nconsole.debug(\"worker\", \"wrap\", wrap);\nconsole.debug(\"worker\", \"xworker\", xworker);\n}\n});\nhooks.worker.onBeforeRun.add(() => {\nconsole.log(\"worker\", \"onBeforeRun\");\n});\nhooks.worker.codeBeforeRun.add('print(\"worker\", \"codeBeforeRun\")');\nhooks.worker.codeAfterRun.add('print(\"worker\", \"codeAfterRun\")');\nhooks.worker.onAfterRun.add(() => {\nconsole.log(\"worker\", \"onAfterRun\");\n});\n
Include the plugin in the web page before including PyScript.<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n<meta charset=\"UTF-8\">\n<meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">\n<!-- JS plugins should be available before PyScript bootstraps -->\n<script type=\"module\" src=\"./log.js\"></script>\n<!-- PyScript -->\n<link rel=\"stylesheet\" href=\"https://pyscript.net/releases/2024.9.1/core.css\">\n<script type=\"module\" src=\"https://pyscript.net/releases/2024.9.1/core.js\"></script>\n</head>\n<body>\n<script type=\"mpy\">\nprint(\"ACTUAL CODE\")\n</script>\n</body>\n</html>\n
"},{"location":"user-guide/running-offline/","title":"Running PyScript Offline","text":"Although users will want to create and share PyScript apps on the internet, there are cases when user want to run PyScript applications offline, in an airgapped fashion. This means that both PyScript core and the interpreter used to run code need to be served with the application itself. In short, the 2 main explicit tasks needed to create an offline PyScript application are:
core.js
)core.js
","text":"There are at least 2 ways to use PyScript offline:
./dist/
folderIn the examples below, we'll assume we are creating a PyScript Application folder called pyscript-offline
and we'll add all the necessary files to the folder.
First of all, we are going to create a pyscript-offline
folder as reference.
mkdir -p pyscript-offline\ncd pyscript-offline\n
"},{"location":"user-guide/running-offline/#adding-core-by-cloning-the-repository","title":"Adding core by Cloning the Repository","text":"You can build all the PyScript Core files by cloning the project repository and building them yourself. To do so, build the files by following the instructions in our developer guide
Once you've run the build
command, copy the build
folder that has been created into your pyscript-offline
folder.
@pyscript/core
Locally","text":"First of all, ensure you are in the folder you would like to test PyScirpt locally. In this case, the pyscript-offline
folder we created earlier.
Once within the folder, be sure there is a package.json
file. Even an empty one with just {}
as content would work. This is needed to be sure the folder will include locally the npm_modules
folder instead of placing the package in the parent folder, if any.
# only if there is no package.json, create one\necho '{}' > ./package.json\n\n# install @pyscript/core\nnpm i @pyscript/core\n
At this point the folder should contain a node_module
in it and we can actually copy its dist
folder wherever we like.
# create a public folder to serve locally\nmkdir -p public\n\n# move @pyscript/core dist into such folder\ncp -R ./node_modules/@pyscript/core/dist ./public/pyscript\n
"},{"location":"user-guide/running-offline/#setting-up-your-application","title":"Setting up your application","text":"Once you've added PyScript code following one of the methods above, that's almost it! We are half way through our goal but we can already create a ./public/index.html
file that loads the project:
<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n<meta charset=\"UTF-8\">\n<meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">\n<title>PyScript Offline</title>\n<script type=\"module\" src=\"/pyscript/core.js\"></script>\n<link rel=\"stylesheet\" href=\"/pyscript/core.css\">\n</head>\n<body>\n<script type=\"mpy\">\nfrom pyscript import document\ndocument.body.append(\"Hello from PyScript\")\n</script>\n</body>\n</html>\n
To run this project directly, after being sure that index.html
file is saved into the public
folder, you can try:
python3 -m http.server -d ./public/\n
Alternatively, if you would like to test also worker
features, you can try instead:
npx static-handler --coi ./public/\n
"},{"location":"user-guide/running-offline/#downloading-and-setting-up-a-local-interpreter","title":"Downloading and Setting up a Local Interpreter","text":"Good news! We are almost there. Now that we've:
we need to download and setup up an interpreter. PyScript officially supports MicroPython and Pyodide interpreters, so let's see how to do that for each one of them.
"},{"location":"user-guide/running-offline/#download-micropython-locally","title":"Download MicroPython locally","text":"Similarly to what we did for @pyscript/core
, we can also install MicroPython from npm:
npm i @micropython/micropython-webassembly-pyscript\n
Our node_modules
folder now should contain a @micropython
one and from there we can move relevant files into our public
folder, but let's be sure we have a target for that:
# create a folder in our public space\nmkdir -p ./public/micropython\n\n# copy related files into such folder\ncp ./node_modules/@micropython/micropython-webassembly-pyscript/micropython.* ./public/micropython/\n
That folder should contain at least both micropython.mjs
and micropython.wasm
files and these are the files we are going to use locally via our dedicated config.
<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n<meta charset=\"UTF-8\">\n<meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">\n<title>PyScript Offline</title>\n<script type=\"module\" src=\"/pyscript/core.js\"></script>\n<link rel=\"stylesheet\" href=\"/pyscript/core.css\">\n</head>\n<body>\n<mpy-config>\n interpreter = \"/micropython/micropython.mjs\"\n </mpy-config>\n<script type=\"mpy\">\nfrom pyscript import document\ndocument.body.append(\"Hello from PyScript\")\n</script>\n</body>\n</html>\n
"},{"location":"user-guide/running-offline/#install-pyodide-locally","title":"Install Pyodide locally","text":"Currently there is a difference between MicroPython and Pyodide: the former does not have (yet) a package manager while the latest does, it's called micropip.
This is important to remember because while the procedure to have pyodide offline is very similar to the one we've just seen, if we want to use also 3rd party packages we also need to have these running locally ... but let's start simple:
# install locally the pyodide module\nnpm i pyodide\n\n# create a folder in our public space\nmkdir -p ./public/pyodide\n\n# move all necessary files into that folder\ncp ./node_modules/pyodide/pyodide* ./public/pyodide/\ncp ./node_modules/pyodide/python_stdlib.zip ./public/pyodide/\n
Please note that also pyodide-lock.json
file is needed so please don't change that cp
operation as all pyodide*
files need to be moved.
At this point, all we need to do is to change our HTML page to use pyodide instead:
<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n<meta charset=\"UTF-8\">\n<meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">\n<title>PyScript Offline</title>\n<script type=\"module\" src=\"/pyscript/core.js\"></script>\n<link rel=\"stylesheet\" href=\"/pyscript/core.css\">\n</head>\n<body>\n<py-config>\n interpreter = \"/pyodide/pyodide.mjs\"\n </py-config>\n<script type=\"py\">\nfrom pyscript import document\ndocument.body.append(\"Hello from PyScript\")\n</script>\n</body>\n</html>\n
"},{"location":"user-guide/running-offline/#wrapping-it-up","title":"Wrapping it up","text":"We are basically done! If we try to disconnect from the internet but we still run our local server, the page will still show that very same Hello from PyScript message :partying_face:
We can now drop internet, still keeping the local server running, and everything should be fine :partying_face:
"},{"location":"user-guide/running-offline/#local-pyodide-packages","title":"Local Pyodide Packages","text":"There's one last thing that users are probably going to need: the ability to install Python packages when using Pyodide.
In order to have also 3rd party packages available, we can use the bundle from pyodide releases that contains also packages.
Please note this bundle is more than 200MB: it not downloaded all at once, it contains each package that is required and it loads only related packages when needed.
Once downloaded and extracted, where in this case I am using 0.24.1
as reference bundle, we can literally copy and paste, or even move, all those files and folders inside the pyodide-0.24.1/pyodide/*
directory into our ./public/pyodide/*
folder.
As the bundle contains files already present, feel free to either skip or replace the content, or even directly move that pyodide folder inside our ./public/
one.
Once it's done, we can now use any package we like that is available in pyodide. Let's see an example:
<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n<meta charset=\"UTF-8\">\n<meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">\n<title>PyScript Offline</title>\n<script type=\"module\" src=\"/pyscript/core.js\"></script>\n<link rel=\"stylesheet\" href=\"/pyscript/core.css\">\n</head>\n<body>\n<py-config>\n interpreter = \"/pyodide/pyodide.mjs\"\n packages = [\"pandas\"]\n </py-config>\n<script type=\"py\">\nimport pandas as pd\nx = pd.Series([1,2,3,4,5,6,7,8,9,10])\nfrom pyscript import document\ndocument.body.append(str([i**2 for i in x]))\n</script>\n</body>\n</html>\n
If everything went fine, we should now be able to read [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
on the page even if we disconnect from the Internet.
And that's all folks :wave:
"},{"location":"user-guide/terminal/","title":"Terminal","text":"In conventional (non-browser based) Python, it is common to run scripts from the terminal, or to interact directly with the Python interpreter via the REPL. It's to the terminal that print
writes characters (via stdout
), and it's from the terminal that the input
reads characters (via stdin
).
It usually looks something like this:
Because of the historic importance of the use of a terminal, PyScript makes one available in the browser (based upon XTerm.js). As mentioned earlier, PyScript's built-in terminal is activated with the terminal
flag when using the <script>
, <py-script>
or <mpy-script>
tags.
Success
As of the 2024.4.1 release, MicroPython works with the terminal.
This is, perhaps, the simplest use case that allows data to be emitted to a read-only terminal:
<script type=\"py\" terminal>print(\"hello world\")</script>\n
The end result will look like this (the rectangular box indicates the current position of the cursor):
Should you need an interactive terminal, for example because you use the input
statement that requires the user to type things into the terminal, you must ensure your code is run on a worker:
<script type=\"py\" terminal worker>\nname = input(\"What is your name? \")\nprint(f\"Hello, {name}\")\n</script>\n
To use the interactive Python REPL in the terminal, use Python's code module like this:
import code\ncode.interact()\n
The end result should look something like this:
Finally, it is possible to dynamically pass Python code into the terminal. The trick is to get a reference to the terminal created by PyScript. Thankfully, this is very easy.
Consider this fragment:
<script id=\"my_script\" type=\"mpy\" terminal worker></script>\n
Get a reference to the element, and just call the process
method on that object:
const myterm = document.querySelector(\"#my_script\");\nawait myterm.process('print(\"Hello world!\")');\n
"},{"location":"user-guide/terminal/#xterm-reference","title":"XTerm reference","text":"Each terminal has a reference to the Terminal instance used to bootstrap the current terminal.
On the JavaScript side, it's a script.terminal
property while on the Python side, it's a __terminal__
special reference that guarantees to provide the very same script.terminal
:
<script id=\"py-terminal\" type=\"py\" terminal worker>\nfrom pyscript import document, ffi\n# example: change default font-family\n__terminal__.options = ffi.to_js({\"fontFamily\": \"cursive\"})\nscript = document.getElementById(\"py-terminal\")\nprint(script.terminal == __terminal__)\n# prints True with the defined font\n</script>\n
"},{"location":"user-guide/terminal/#clear-the-terminal","title":"Clear the terminal","text":"It's very simple to clear a PyTerminal:
Clearing the terminal<script type=\"mpy\" terminal worker>\nprint(\"before\")\n__terminal__.clear()\nprint(\"after\")\n# only \"after\" is on the terminal\n</script>\n
"},{"location":"user-guide/terminal/#terminal-colors","title":"Terminal colors","text":"Colors and most special characters work so you can make the text bold or turn it green. You could even use a control character to print('\\033[2J')
and clear the terminal, instead of using the exposed clear()
method:
<script type=\"mpy\" terminal worker>\nprint(\"This is \\033[1mbold\\033[0m\")\nprint(\"This is \\033[32mgreen\\033[0m\")\nprint(\"This is \\033[1m\\033[35mbold and purple\\033[0m\")\n</script>\n
"},{"location":"user-guide/terminal/#terminal-addons","title":"Terminal addons","text":"It's possible use XTerm.js addons:
Terminal addons<py-config>\n [js_modules.main]\n \"https://cdn.jsdelivr.net/npm/@xterm/addon-web-links/+esm\" = \"weblinks\"\n</py-config>\n<script type=\"py\" terminal>\nfrom pyscript import js_modules\naddon = js_modules.weblinks.WebLinksAddon.new()\n__terminal__.loadAddon(addon)\nprint(\"Check out https://pyscript.net/\")\n</script>\n
By default we enable the WebLinksAddon
addon (so URLs displayed in the terminal automatically become links). Behind the scenes is the example code shown above, and this approach will work for any other addon you may wish to use.
MicroPython has a very complete REPL already built into it.
Ctrl+X
strokes are handled, including paste mode and kill switches.tab
key to see available variables or objects in globals
.As a bonus, the MicroPython terminal works on both the main thread and in web workers, with the following caveats:
input
function are delegated to the native browser based prompt utility.while True:
loops). Such blocking code could freeze your page.input
function, without blocking the main thread.while True:
loops) does not block the main thread and your page will remain responsive.We encourage the usage of worker
attribute to bootstrap a MicroPython terminal. But now you have an option to run the terminal in the main thread. Just remember not to block!
PyScript is an open source platform for Python in the browser.
PyScript brings together two of the most vibrant technical ecosystems on the planet. If the web and Python had a baby, you'd get PyScript.
PyScript works because modern browsers support WebAssembly (abbreviated to WASM) - an instruction set for a virtual machine with an open specification and near native performance. PyScript takes versions of the Python interpreter compiled to WASM, and makes them easy to use inside the browser.
At the core of PyScript is a philosophy of digital empowerment. The web is the world's most ubiquitous computing platform, mature and familiar to billions of people. Python is one of the world's most popular programming languages: it is easy to teach and learn, used in a plethora of existing domains (such as data science, games, embedded systems, artificial intelligence, finance, physics and film production - to name but a few), and the Python ecosystem contains a huge number of popular and powerful libraries to address its many uses.
PyScript brings together the ubiquity, familiarity and accessibility of the web with the power, depth and expressiveness of Python. It means PyScript isn't just for programming experts but, as we like to say, for the 99% of the rest of the planet who use computers.
"},{"location":"user-guide/workers/","title":"Workers","text":"Workers run code that won't block the \"main thread\" controlling the user interface. If you block the main thread, your web page becomes annoyingly unresponsive. You should never block the main thread.
Happily, PyScript makes it very easy to use workers and uses a feature recently added to web standards called Atomics. You don't need to know about Atomics to use web workers, but it's useful to know that the underlying coincident library uses it under the hood.
Info
Sometimes you only need to await
in the main thread on a method in a worker when neither window
nor document
are referenced in the code running on the worker.
In these cases, you don't need any special header or service worker as long as the method exposed from the worker returns a serializable result.
"},{"location":"user-guide/workers/#http-headers","title":"HTTP headers","text":"To use the window
and document
objects from within a worker (i.e. use synchronous Atomics) you must ensure your web server enables the following headers (this is the default behavior for pyscript.com):
Access-Control-Allow-Origin: *\nCross-Origin-Opener-Policy: same-origin\nCross-Origin-Embedder-Policy: require-corp\nCross-Origin-Resource-Policy: cross-origin\n
If you're unable to configure your server's headers, you have two options:
service-worker
attribute with the script
element.For performance reasons, this is the preferred option so Atomics works at native speed.
The simplest way to use mini-coi is to copy the mini-coi.js file content and save it in the root of your website (i.e. /
), and reference it as the first child tag in the <head>
of your HTML documents:
<html>\n<head>\n<script src=\"/mini-coi.js\"></script>\n<!-- etc -->\n</head>\n<!-- etc -->\n</html>\n
"},{"location":"user-guide/workers/#option-2-service-worker-attribute","title":"Option 2: service-worker
attribute","text":"This allows you to slot in a custom service worker to handle requirements for synchronous operations.
Each <script type=\"m/py\">
or <m/py-script>
may optionally have a service-worker
attribute pointing to a locally served file (the same way mini-coi.js
needs to be served).
mini-coi.js
itself or any other custom service worker, as long as it provides either the right headers to enable synchronous operations via Atomics, or it enables sabayon polyfill events.window
and document
access in your worker logic.<html>\n<head>\n<!-- PyScript link and script -->\n</head>\n<body>\n<script type=\"py\" service-worker=\"./sw.js\" worker>\nfrom pyscript import window, document\ndocument.body.append(\"Hello PyScript!\")\n</script>\n</body>\n</html>\n
Warning
Using sabayon as the fallback for synchronous operations via Atomics should be the last solution to consider. It is inevitably slower than using native Atomics.
If you must use sabayon, always reduce the amount of synchronous operations by caching references from the main thread.
# \u274c THIS IS UNNECESSARILY SLOWER\nfrom pyscript import document\n# add a data-test=\"not ideal attribute\"\ndocument.body.dataset.test = \"not ideal\"\n# read a data-test attribute\nprint(document.body.dataset.test)\n# - - - - - - - - - - - - - - - - - - - - -\n# \u2714\ufe0f THIS IS FINE\nfrom pyscript import document\n# if needed elsewhere, reach it once\nbody = document.body\ndataset = body.dataset\n# add a data-test=\"not ideal attribute\"\ndataset.test = \"not ideal\"\n# read a data-test attribute\nprint(dataset.test)\n
In latter example the number of operations has been reduced from six to just four. The rule of thumb is: if you ever need a DOM reference more than once, cache it. \ud83d\udc4d
"},{"location":"user-guide/workers/#start-working","title":"Start working","text":"To start your code in a worker, simply ensure the <script>
, <py-script>
or <mpy-script>
tag pointing to the code you want to run has a worker
attribute flag:
<script type=\"py\" src=\"./my-worker-code.py\" worker></script>\n
You may also want to add a name
attribute to the tag, so you can use pyscript.workers
in the main thread to retrieve a reference to the worker:
<script type=\"py\" src=\"./my-worker-code.py\" worker name=\"my-worker\"></script>\n
from pyscript import workers\nmy_worker = await workers[\"my-worker\"]\n
Alternatively, to launch a worker from within Python running on the main thread use the pyscript.PyWorker class and you must reference both the target Python script and interpreter type:
Launch a worker from within Pythonfrom pyscript import PyWorker\n# The type MUST be given and can be either `micropython` or `pyodide`\nmy_worker = PyWorker(\"my-worker-code.py\", type=\"micropython\")\n
"},{"location":"user-guide/workers/#worker-interactions","title":"Worker interactions","text":"Code running in the worker needs to be able to interact with code running in the main thread and perhaps have access to the web page. This is achieved via some helpful builtin APIs.
Note
For ease of use, the worker related functionality in PyScript is a simpler presentation of more sophisticated and powerful behaviour available via PolyScript.
If you are a confident advanced user, please consult the XWorker related documentation from the PolyScript project for how to make use of these features.
To synchronise serializable data between the worker and the main thread use the sync
function in the worker to reference a function registered on the main thread:
from pyscript import PyWorker\ndef hello(name=\"world\"):\nreturn(f\"Hello, {name}\")\n# Create the worker.\nworker = PyWorker(\"./worker.py\", type=\"micropython\")\n# Register the hello function as callable from the worker.\nworker.sync.hello = hello\n
Python code in the resulting worker.from pyscript import sync, window\ngreeting = sync.hello(\"PyScript\")\nwindow.console.log(greeting)\n
Alternatively, for the main thread to call functions in a worker, specify the functions in a __export__
list:
import sys\ndef version():\nreturn sys.version\n# Define what to export to the main thread.\n__export__ = [\"version\", ]\n
Then ensure you have a reference to the worker in the main thread (for instance, by using the pyscript.workers
):
<script type=\"py\" src=\"./my-worker-code.py\" worker name=\"my-worker\"></script>\n
Referencing and using the worker from the main thread.from pyscript import workers\nmy_worker = await workers[\"my-worker\"]\nprint(await my_worker.version())\n
The values passed between the main thread and the worker must be serializable. Try the example given above via this project on PyScript.com.
No matter if your code is running on the main thread or in a web worker, both the pyscript.window
(representing the main thread's global window context) and pyscript.document
(representing the web page's document object) will be available and work in the same way. As a result, a worker can reach into the DOM and access some window
based APIs.
Warning
Access to the window
and document
objects is a powerful feature. Please remember that:
document
object, and other workers or code on the main thread does so too, they may interfere with each other and produce unforeseen problematic results. Remember, with great power comes great responsibility... and we've given you a bazooka (so please remember not to shoot yourself in the foot with it).While it is possible to start a MicroPython or Pyodide worker from either MicroPython or Pyodide running on the main thread, the most common use case we have encountered is MicroPython on the main thread starting a Pyodide worker.
Here's how:
index.html Evaluate main.py via MicroPython on the main thread
<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n<meta charset=\"utf-8\">\n<meta name=\"viewport\" content=\"width=device-width,initial-scale=1\">\n<!-- PyScript CSS -->\n<link rel=\"stylesheet\" href=\"https://pyscript.net/releases/2024.9.1/core.css\">\n<!-- This script tag bootstraps PyScript -->\n<script type=\"module\" src=\"https://pyscript.net/releases/2024.9.1/core.js\"></script>\n<title>PyWorker - mpy bootstrapping pyodide example</title>\n<script type=\"mpy\" src=\"main.py\"></script>\n</head>\n</html>\n
main.py MicroPython's main.py: bootstrapping a Pyodide worker.
from pyscript import PyWorker, document\n# Bootstrap the Pyodide worker, with optional config too.\n# The worker is:\n# * Owned by this script, no JS or Pyodide code in the same page can access\n# it.\n# * It allows pre-sync methods to be exposed.\n# * It has a ready Promise to await for when Pyodide is ready in the worker. \n# * It allows the use of post-sync (methods exposed by Pyodide in the\n# worker).\nworker = PyWorker(\"worker.py\", type=\"pyodide\")\n# Expose a utility that can be immediately invoked in the worker. \nworker.sync.greetings = lambda: print(\"Pyodide bootstrapped\")\nprint(\"before ready\")\n# Await until Pyodide has completed its bootstrap, and is ready.\nawait worker.ready\nprint(\"after ready\")\n# Await any exposed methods exposed via Pyodide in the worker.\nresult = await worker.sync.heavy_computation()\nprint(result)\n# Show the result at the end of the body.\ndocument.body.append(result)\n# Free memory and get rid of everything in the worker.\nworker.terminate()\n
worker.py The worker.py script runs in the Pyodide worker.
from pyscript import sync\n# Use any methods from main.py on the main thread.\nsync.greetings()\n# Expose any methods meant to be used from main.\nsync.heavy_computation = lambda: 6 * 7\n
Save these files in a tmp
folder, ensure your headers (just use npx mini-coi ./tmp
to serve via localhost) then see the following outcome in the browser's devtools.
before ready\nPyodide bootstrapped\nafter ready\n42\n
"}]}
\ No newline at end of file
+{"config":{"lang":["en"],"separator":"[\\s\\-]+","pipeline":["stopWordFilter"]},"docs":[{"location":"","title":"Home","text":"PyScript is an open source platform for Python in the browser."},{"location":"#pyscript-is","title":"PyScript is...","text":"Welcome, friend! PyScript is an open source project, we expect participants to act in the spirit of our code of conduct and we have many ways in which you can contribute. Our developer guide explains how to set up a working development environment for PyScript.
Just show me... That's easy! Just take a look around pyscript.com - our platform for developing and hosting PyScript applications. By using using this service you help to support and sustain the development and growth of the open-source PyScript project. I want support...Join the conversation on our discord server, for realtime chat with core maintainers and fellow users of PyScript. Check out our YouTube channel, full of community calls and show and tells. Explore educational and commercial support provided by our open source sponsor Anaconda Inc (this helps pay for and sustain PyScript!).
"},{"location":"api/","title":"Built-in APIs","text":"PyScript makes available convenience objects, functions and attributes.
In Python this is done via the builtin pyscript
module:
from pyscript import document\n
In HTML this is done via py-*
and mpy-*
attributes (depending on the interpreter you're using):
<button id=\"foo\" py-click=\"handler_defined_in_python\">Click me</button>\n
These APIs will work with both Pyodide and Micropython in exactly the same way.
Info
Both Pyodide and MicroPython provide access to two further lower-level APIs:
globalThis
via importing the js
module: import js
(now js
is a proxy for globalThis
in which all native JavaScript based browser APIs are found).PyScript can run in two contexts: the main browser thread, or on a web worker. The following three categories of API functionality explain features that are common for both main thread and worker, main thread only, and worker only. Most features work in both contexts in exactly the same manner, but please be aware that some are specific to either the main thread or a worker context.
"},{"location":"api/#common-features","title":"Common features","text":"These Python objects / functions are available in both the main thread and in code running on a web worker:
"},{"location":"api/#pyscriptconfig","title":"pyscript.config
","text":"A Python dictionary representing the configuration for the interpreter.
Reading the current configuration.from pyscript import config\n# It's just a dict.\nprint(config.get(\"files\"))\n
Warning
Changing the config
dictionary at runtime has no effect on the actual configuration.
It's just a convenience to read the configuration at run time.
"},{"location":"api/#pyscriptcurrent_target","title":"pyscript.current_target
","text":"A utility function to retrieve the unique identifier of the element used to display content. If the element is not a <script>
and it already has an id
, that id
will be returned.
<!-- current_target(): explicit-id -->\n<mpy-script id=\"explicit-id\">\n from pyscript import display, current_target\n display(f\"current_target(): {current_target()}\")\n</mpy-script>\n<!-- current_target(): mpy-0 -->\n<mpy-script>\n from pyscript import display, current_target\n display(f\"current_target(): {current_target()}\")\n</mpy-script>\n<!-- current_target(): mpy-1 -->\n<!-- creates right after the <script>:\n <script-py id=\"mpy-1\">\n <div>current_target(): mpy-1</div>\n </script-py>\n-->\n<script type=\"mpy\">\nfrom pyscript import display, current_target\ndisplay(f\"current_target(): {current_target()}\")\n</script>\n
Note
The return value of current_target()
always references a visible element on the page, not at the current <script>
that is executing the code.
To reference the <script>
element executing the code, assign it an id
:
<script type=\"mpy\" id=\"unique-id\">...</script>\n
Then use the standard document.getElementById(script_id)
function to return a reference to it in your code.
pyscript.display
","text":"A function used to display content. The function is intelligent enough to introspect the object[s] it is passed and work out how to correctly display the object[s] in the web page based on the following mime types:
text/plain
to show the content as texttext/html
to show the content as HTMLimage/png
to show the content as <img>
image/jpeg
to show the content as <img>
image/svg+xml
to show the content as <svg>
application/json
to show the content as JSONapplication/javascript
to put the content in <script>
(discouraged)The display
function takes a list of *values
as its first argument, and has two optional named arguments:
target=None
- the DOM element into which the content should be placed. If not specified, the target
will use the current_script()
returned id and populate the related dedicated node to show the content.append=True
- a flag to indicate if the output is going to be appended to the target
.There are some caveats:
display
function automatically uses the current <py-script>
or <mpy-script>
tag as the target
into which the content will be displayed.<script>
tag has the target
attribute, and is not a worker, the element on the page with that ID (or which matches that selector) will be used to display the content instead.display
function needs an explicit target=\"dom-id\"
argument to identify where the content will be displayed.append=True
is the default behaviour.<!-- will produce\n <py-script>PyScript</py-script>\n-->\n<py-script worker>\n from pyscript import display\n display(\"PyScript\", append=False)\n</py-script>\n<!-- will produce\n <script type=\"py\">...</script>\n <script-py>PyScript</script-py>\n-->\n<script type=\"py\">\nfrom pyscript import display\ndisplay(\"PyScript\", append=False)\n</script>\n<!-- will populate <h1>PyScript</h1> -->\n<script type=\"py\" target=\"my-h1\">\nfrom pyscript import display\ndisplay(\"PyScript\", append=False)\n</script>\n<h1 id=\"my-h1\"></h1>\n<!-- will populate <h2>PyScript</h2> -->\n<script type=\"py\" worker>\nfrom pyscript import display\ndisplay(\"PyScript\", target=\"my-h2\", append=False)\n</script>\n<h2 id=\"my-h2\"></h2>\n
"},{"location":"api/#pyscriptdocument","title":"pyscript.document
","text":"On both main and worker threads, this object is a proxy for the web page's document object. The document
is a representation of the DOM and can be used to read or manipulate the content of the web page.
pyscript.fetch
","text":"A common task is to fetch
data from the web via HTTP requests. The pyscript.fetch
function provides a uniform way to achieve this in both Pyodide and MicroPython. It is closely modelled on the Fetch API found in browsers with some important Pythonic differences.
The simple use case is to pass in a URL and await
the response. If this request is in a function, that function should also be defined as async
.
from pyscript import fetch\nresponse = await fetch(\"https://example.com\")\nif response.ok:\ndata = await response.text()\nelse:\nprint(response.status)\n
The object returned from an await fetch
call will have attributes that correspond to the JavaScript response object. This is useful for getting response codes, headers and other metadata before processing the response's data.
Alternatively, rather than using a double await
(one to get the response, the other to grab the data), it's possible to chain the calls into a single await
like this:
from pyscript import fetch\ndata = await fetch(\"https://example.com\").text()\n
The following awaitable methods are available to you to access the data returned from the server:
arrayBuffer()
returns a Python memoryview of the response. This is equivalent to the arrayBuffer()
method in the browser based fetch
API.blob()
returns a JavaScript blob
version of the response. This is equivalent to the blob()
method in the browser based fetch
API.bytearray()
returns a Python bytearray
version of the response.json()
returns a Python datastructure representing a JSON serialised payload in the response.text()
returns a Python string version of the response.The underlying browser fetch
API has many request options that you should simply pass in as keyword arguments like this:
from pyscript import fetch\nresult = await fetch(\"https://example.com\", method=\"POST\", body=\"HELLO\").text()\n
Danger
You may encounter CORS errors (especially with reference to a missing Access-Control-Allow-Origin header.
This is a security feature of modern browsers where the site to which you are making a request will not process a request from a site hosted at another domain.
For example, if your PyScript app is hosted under example.com
and you make a request to bbc.co.uk
(who don't allow requests from other domains) then you'll encounter this sort of CORS related error.
There is nothing PyScript can do about this problem (it's a feature, not a bug). However, you could use a pass-through proxy service to get around this limitation (i.e. the proxy service makes the call on your behalf).
"},{"location":"api/#pyscriptffi","title":"pyscript.ffi
","text":"The pyscript.ffi
namespace contains foreign function interface (FFI) methods that work in both Pyodide and MicroPython.
pyscript.ffi.create_proxy
","text":"A utility function explicitly for when a callback function is added via an event listener. It ensures the function still exists beyond the assignment of the function to an event. Should you not create_proxy
around the callback function, it will be immediately garbage collected after being bound to the event.
Warning
There is some technical complexity to this situation, and we have attempted to create a mechanism where create_proxy
is never needed.
Pyodide expects the created proxy to be explicitly destroyed when it's not needed / used anymore. However, the underlying proxy.destroy()
method has not been implemented in MicroPython (yet).
To simplify this situation and automatically destroy proxies based on JavaScript memory management (garbage collection) heuristics, we have introduced an experimental flag:
experimental_create_proxy = \"auto\"\n
This flag ensures the proxy creation and destruction process is managed for you. When using this flag you should never need to explicitly call create_proxy
.
The technical details of how this works are described here.
"},{"location":"api/#pyscriptffito_js","title":"pyscript.ffi.to_js
","text":"A utility function to convert Python references into their JavaScript equivalents. For example, a Python dictionary is converted into a JavaScript object literal (rather than a JavaScript Map
), unless a dict_converter
is explicitly specified and the runtime is Pyodide.
The technical details of how this works are described here.
"},{"location":"api/#pyscriptjs_modules","title":"pyscript.js_modules
","text":"It is possible to define JavaScript modules to use within your Python code.
Such named modules will always then be available under the pyscript.js_modules
namespace.
Warning
Please see the documentation (linked above) about restrictions and gotchas when configuring how JavaScript modules are made available to PyScript.
"},{"location":"api/#pyscriptstorage","title":"pyscript.storage
","text":"The pyscript.storage
API wraps the browser's built-in IndexDB persistent storage in a synchronous Pythonic API.
Info
The storage API is persistent per user tab, page, or domain, in the same way IndexedDB persists.
This API is not saving files in the interpreter's virtual file system nor onto the user's hard drive.
from pyscript import storage\n# Each store must have a meaningful name.\nstore = await storage(\"my-storage-name\")\n# store is a dictionary and can now be used as such.\n
The returned dictionary automatically loads the current state of the referenced IndexDB. All changes are automatically queued in the background.
# This is a write operation.\nstore[\"key\"] = value\n# This is also a write operation (it changes the stored data).\ndel store[\"key\"]\n
Should you wish to be certain changes have been synchronized to the underlying IndexDB, just await store.sync()
.
Common types of value can be stored via this API: bool
, float
, int
, str
and None
. In addition, data structures like list
, dict
and tuple
can be stored.
Warning
Because of the way the underlying data structure are stored in IndexDB, a Python tuple
will always be returned as a Python list
.
It is even possible to store arbitrary data via a bytearray
or memoryview
object. However, there is a limitation that such values must be stored as a single key/value pair, and not as part of a nested data structure.
Sometimes you may need to modify the behaviour of the dict
like object returned by pyscript.storage
. To do this, create a new class that inherits from pyscript.Storage
, then pass in your class to pyscript.storage
as the storage_class
argument:
from pyscript import window, storage, Storage\nclass MyStorage(Storage):\ndef __setitem__(self, key, value):\nsuper().__setitem__(key, value)\nwindow.console.log(key, value)\n...\nstore = await storage(\"my-data-store\", storage_class=MyStorage)\n# The store object is now an instance of MyStorage.\n
"},{"location":"api/#pyscriptcorediststoragejs","title":"@pyscript/core/dist/storage.js
","text":"The equivalent functionality based on the JS module can be found through our module.
The goal is to be able to share the same database across different worlds (interpreters) and the functionality is nearly identical except there is no class to provide because the storage in JS is just a dictionary proxy that synchronizes behind the scene all read, write or delete operations.
"},{"location":"api/#pyscriptweb","title":"pyscript.web
","text":"The classes and references in this namespace provide a Pythonic way to interact with the DOM. An explanation for how to idiomatically use this API can be found in the user guide
"},{"location":"api/#pyscriptwebpage","title":"pyscript.web.page
","text":"This object represents a web page. It has four attributes and two methods:
html
- a reference to a Python object representing the document's html root element.head
- a reference to a Python object representing the document's head.body
- a reference to a Python object representing the document's body.title
- the page's title (usually displayed in the browser's title bar or a page's tab.find
- a method that takes a single selector argument and returns a collection of Python objects representing the matching elements.append
- a shortcut for page.body.append
(to add new elements to the page).You may also shortcut the find
method by enclosing a CSS selector in square brackets: page[\"#my-thing\"]
.
These are provided as a convenience so you have several simple and obvious options for accessing and changing the content of the page.
All the Python objects returned by these attributes and method are instances of classes relating to HTML elements defined in the pyscript.web
namespace.
pyscript.web.*
","text":"There are many classes in this namespace. Each is a one-to-one mapping of any HTML element name to a Python class representing the HTML element of that name. Each Python class ensures only valid properties and attributes can be assigned, according to web standards.
Usage of these classes is explained in the user guide.
Info
The full list of supported element/class names is:
grid\na, abbr, address, area, article, aside, audio\nb, base, blockquote, body, br, button\ncanvas, caption, cite, code, col, colgroup\ndata, datalist, dd, del_, details, dialog, div, dl, dt\nem, embed\nfieldset, figcaption, figure, footer, form\nh1, h2, h3, h4, h5, h6, head, header, hgroup, hr, html\ni, iframe, img, input_, ins\nkbd\nlabel, legend, li, link\nmain, map_, mark, menu, meta, meter\nnav\nobject_, ol, optgroup, option, output\np, param, picture, pre, progress\nq\ns, script, section, select, small, source, span, strong, style, sub, summary, sup\ntable, tbody, td, template, textarea, tfoot, th, thead, time, title, tr, track\nu, ul\nvar, video\nwbr\n
These correspond to the standard HTML elements with the caveat that del_
and input_
have the trailing underscore (_
) because they are also keywords in Python, and the grid
is a custom class for a div
with a grid
style display
property.
All these classes ultimately derive from the pyscript.web.elements.Element
base class.
In addition to properties defined by the HTML standard for each type of HTML element (e.g. title
, src
or href
), all elements have the following properties and methods (in alphabetical order):
append(child)
- add the child
element to the element's children.children
- a collection containing the element's child elements (that it contains).classes
- a set of CSS classes associated with the element.clone(clone_id=None)
- Make a clone of the element (and the underlying DOM object), and assign it the optional clone_id
.find(selector)
- use a CSS selector to find matching child elements.parent
- the element's parent element (that contains it).show_me
- scroll the element into view.style
- a dictionary of CSS style properties associated with the element.update(classes=None, style=None, **kwargs)
- update the element with the specified classes (set), style (dict) and DOM properties (kwargs)._dom_element
- a reference to the proxy object that represents the underlying native HTML element.Info
All elements, by virtue of inheriting from the base Element
class, may have the following properties:
accesskey, autofocus, autocapitalize,\nclassName, contenteditable,\ndraggable,\nenterkeyhint,\nhidden,\ninnerHTML, id,\nlang,\nnonce,\npart, popover,\nslot, spellcheck,\ntabindex, text, title, translate,\nvirtualkeyboardpolicy\n
The classes
set-like object has the following convenience functions:
add(*class_names)
- add the class(es) to the element.contains(class_name)
- indicate if class_name
is associated with the element.remove(*class_names)
- remove the class(es) from the element.replace(old_class, new_class)
- replace the old_class
with new_class
.toggle(class_name)
- add a class if it is absent, or remove a class if it is present.Elements that require options (such as the datalist
, optgroup
and select
elements), can have options passed in when they are created:
my_select = select_(option(\"apple\", value=1), option(\"pear\"))\n
Notice how options can be a tuple of two values (the name and associated value) or just the single name (whose associated value will default to the given name).
It's possible to access and manipulate the options
of the resulting elements:
selected_option = my_select.options.selected\nmy_select.options.remove(0) # Remove the first option (in position 0).\nmy_select.clear()\nmy_select.options.add(html=\"Orange\")\n
Finally, the collection of elements returned by find
and children
is iterable, indexable and sliceable:
for child in my_element.children[10:]:\nprint(child.html)\n
Furthermore, four attributes related to all elements contained in the collection can be read (as a list) or set (applied to all contained elements):
classes
- the list of classes associated with the elements.innerHTML
- the innerHTML of each element.style
- a dictionary like object for interacting with CSS style rules.value
- the value
attribute associated with each element.pyscript.when
","text":"A Python decorator to indicate the decorated function should handle the specified events for selected elements.
The decorator takes two parameters:
event_type
should be the name of the browser event to handle as a string (e.g. \"click\"
).selector
should be a string containing a valid selector to indicate the target elements in the DOM whose events of event_type
are of interest.The following example has a button with an id of my_button
and a decorated function that handles click
events dispatched by the button.
<button id=\"my_button\">Click me!</button>\n
The decorated Python function to handle click eventsfrom pyscript import when, display\n@when(\"click\", \"#my_button\")\ndef click_handler(event):\n\"\"\"\n Event handlers get an event object representing the activity that raised\n them.\n \"\"\"\ndisplay(\"I've been clicked!\")\n
This functionality is related to the py-*
or mpy-*
HTML attributes.
pyscript.window
","text":"On the main thread, this object is exactly the same as import js
which, in turn, is a proxy of JavaScript's globalThis object.
On a worker thread, this object is a proxy for the web page's global window context.
Warning
The reference for pyscript.window
is always a reference to the main thread's global window context.
If you're running code in a worker this is not the worker's own global context. A worker's global context is always reachable via import js
(the js
object being a proxy for the worker's globalThis
).
pyscript.HTML
","text":"A class to wrap generic content and display it as un-escaped HTML on the page.
The HTML class<script type=\"mpy\">\nfrom pyscript import display, HTML\n# Escaped by default:\ndisplay(\"<em>em</em>\") # <em>em</em>\n</script>\n<script type=\"mpy\">\nfrom pyscript import display, HTML\n# Un-escaped raw content inserted into the page:\ndisplay(HTML(\"<em>em</em>\")) # <em>em</em>\n</script>\n
"},{"location":"api/#pyscriptrunning_in_worker","title":"pyscript.RUNNING_IN_WORKER
","text":"This constant flag is True
when the current code is running within a worker. It is False
when the code is running within the main thread.
pyscript.WebSocket
","text":"If a pyscript.fetch
results in a call and response HTTP interaction with a web server, the pyscript.Websocket
class provides a way to use websockets for two-way sending and receiving of data via a long term connection with a web server.
PyScript's implementation, available in both the main thread and a web worker, closely follows the browser's own WebSocket class.
This class accepts the following named arguments:
url
pointing at the ws or wss address. E.g.: WebSocket(url=\"ws://localhost:5037/\")
protocols
, an optional string or a list of strings as described here.The WebSocket
class also provides these convenient static constants:
WebSocket.CONNECTING
(0
) - the ws.readyState
value when a web socket has just been created.WebSocket.OPEN
(1
) - the ws.readyState
value once the socket is open.WebSocket.CLOSING
(2
) - the ws.readyState
after ws.close()
is explicitly invoked to stop the connection.WebSocket.CLOSED
(3
) - the ws.readyState
once closed.A WebSocket
instance has only 2 methods:
ws.send(data)
- where data
is either a string or a Python buffer, automatically converted into a JavaScript typed array. This sends data via the socket to the connected web server.ws.close(code=0, reason=\"because\")
- which optionally accepts code
and reason
as named arguments to signal some specific status or cause for closing the web socket. Otherwise ws.close()
works with the default standard values.A WebSocket
instance also has the fields that the JavaScript WebSocket
instance will have:
send()
but not yet transmitted to the network.WebSocket
static constants (CONNECTING
, OPEN
, etc...).WebSocket
instance.A WebSocket
instance can have the following listeners. Directly attach handler functions to them. Such functions will always receive a single event
object.
WebSocket
's connection is closed.WebSocket
. If the event.data
is a JavaScript typed array instead of a string, the reference it will point directly to a memoryview of the underlying bytearray
data.The following code demonstrates a pyscript.WebSocket
in action.
<script type=\"mpy\" worker>\nfrom pyscript import WebSocket\ndef onopen(event):\nprint(event.type)\nws.send(\"hello\")\ndef onmessage(event):\nprint(event.type, event.data)\nws.close()\ndef onclose(event):\nprint(event.type)\nws = WebSocket(url=\"ws://localhost:5037/\")\nws.onopen = onopen\nws.onmessage = onmessage\nws.onclose = onclose\n</script>\n
Info
It's also possible to pass in any handler functions as named arguments when you instantiate the pyscript.WebSocket
class:
from pyscript import WebSocket\ndef onmessage(event):\nprint(event.type, event.data)\nws.close()\nws = WebSocket(url=\"ws://example.com/socket\", onmessage=onmessage)\n
"},{"location":"api/#pyscriptjs_import","title":"pyscript.js_import
","text":"If a JavaScript module is only needed under certain circumstances, we provide an asynchronous way to import packages that were not originally referenced in your configuration.
A pyscript.js_import example.<script type=\"py\">\nfrom pyscript import js_import, window\nescaper, = await js_import(\"https://esm.run/html-escaper\")\n\nwindow.console.log(escaper)\n
The js_import
call returns an asynchronous tuple containing the JavaScript modules referenced as string arguments.
pyscript.py_import
","text":"Warning
This is an experimental feature.
Feedback and bug reports are welcome!
If you have a lot of Python packages referenced in your configuration, startup performance may be degraded as these are downloaded.
If a Python package is only needed under certain circumstances, we provide an asynchronous way to import packages that were not originally referenced in your configuration.
A pyscript.py_import example.<script type=\"py\">\nfrom pyscript import py_import\nmatplotlib, regex, = await py_import(\"matplotlib\", \"regex\")\nprint(matplotlib, regex)\n</script>\n
The py_import
call returns an asynchronous tuple containing the Python modules provided by the packages referenced as string arguments.
pyscript.PyWorker
","text":"A class used to instantiate a new worker from within Python.
Note
Sometimes we disambiguate between interpreters through naming conventions (e.g. py
or mpy
).
However, this class is always PyWorker
and the desired interpreter MUST be specified via a type
option. Valid values for the type of interpreter are either micropython
or pyodide
.
The following fragments demonstrate how to evaluate the file worker.py
on a new worker from within Python.
from pyscript import RUNNING_IN_WORKER, display, sync\ndisplay(\"Hello World\", target=\"output\", append=True)\n# will log into devtools console\nprint(RUNNING_IN_WORKER) # True\nprint(\"sleeping\")\nsync.sleep(1)\nprint(\"awake\")\n
main.py - starts a new worker in Python.from pyscript import PyWorker\n# type MUST be either `micropython` or `pyodide`\nPyWorker(\"worker.py\", type=\"micropython\")\n
The HTML context for the worker.<script type=\"mpy\" src=\"./main.py\">\n<div id=\"output\"></div> <!-- The display target -->\n
"},{"location":"api/#pyscriptworkers","title":"pyscript.workers
","text":"The pyscript.workers
reference allows Python code in the main thread to easily access named workers (and their exported functionality).
For example, the following Pyodide code may be running on a named worker (see the name
attribute of the script
tag):
<script type=\"py\" worker name=\"py-version\">\nimport sys\ndef version():\nreturn sys.version\n# define what to export to main consumers\n__export__ = [\"version\"]\n</script>\n
While over on the main thread, this fragment of MicroPython will be able to access the worker's version
function via the workers
reference:
<script type=\"mpy\">\nfrom pyscript import workers\npyworker = await workers[\"py-version\"]\n# print the pyodide version\nprint(await pyworker.version())\n</script>\n
Importantly, the workers
reference will NOT provide a list of known workers, but will only await
for a reference to a named worker (resolving when the worker is ready). This is because the timing of worker startup is not deterministic.
Should you wish to await for all workers on the page at load time, it's possible to loop over matching elements in the document like this:
<script type=\"mpy\">\nfrom pyscript import document, workers\nfor el in document.querySelectorAll(\"[type='py'][worker][name]\"):\nawait workers[el.getAttribute('name')]\n# ... rest of the code\n</script>\n
"},{"location":"api/#worker-only-features","title":"Worker only features","text":""},{"location":"api/#pyscriptsync","title":"pyscript.sync
","text":"A function used to pass serializable data from workers to the main thread.
Imagine you have this code on the main thread:
Python code on the main threadfrom pyscript import PyWorker\ndef hello(name=\"world\"):\ndisplay(f\"Hello, {name}\")\nworker = PyWorker(\"./worker.py\")\nworker.sync.hello = hello\n
In the code on the worker, you can pass data back to handler functions like this:
Pass data back to the main thread from a workerfrom pyscript import sync\nsync.hello(\"PyScript\")\n
"},{"location":"api/#html-attributes","title":"HTML attributes","text":"As a convenience, and to ensure backwards compatibility, PyScript allows the use of inline event handlers via custom HTML attributes.
Warning
This classic pattern of coding (inline event handlers) is no longer considered good practice in web development circles.
We include this behaviour for historic reasons, but the folks at Mozilla have a good explanation of why this is currently considered bad practice.
These attributes, expressed as py-*
or mpy-*
attributes of an HTML element, reference the name of a Python function to run when the event is fired. You should replace the *
with the actual name of an event (e.g. py-click
or mpy-click
). This is similar to how all event handlers on elements start with on
in standard HTML (e.g. onclick
). The rule of thumb is to simply replace on
with py-
or mpy-
and then reference the name of a Python function.
<button py-click=\"handle_click\" id=\"my_button\">Click me!</button>\n
The related Python function.from pyscript import window\ndef handle_click(event):\n\"\"\"\n Simply log the click event to the browser's console.\n \"\"\"\nwindow.console.log(event) \n
Under the hood, the pyscript.when
decorator is used to enable this behaviour.
Note
In earlier versions of PyScript, the value associated with the attribute was simply evaluated by the Python interpreter. This was unsafe: manipulation of the attribute's value could have resulted in the evaluation of arbitrary code.
This is why we changed to the current behaviour: just supply the name of the Python function to be evaluated, and PyScript will do this safely.
"},{"location":"beginning-pyscript/","title":"Beginning PyScript","text":"PyScript is a platform for running Python in modern web browsers.
Create apps with a PyScript development environment: write code, curate the project's assets, and test your application.
To distribute a PyScript application, host it on the web, then click on the link to your application. PyScript and the browser do the rest.
This page covers these core aspects of PyScript in a beginner friendly manner. We only assume you know how to use a browser and edit text.
Note
The easiest way to get a PyScript development environment and hosting, is to use pyscript.com in your browser.
It is a free service that helps you create new projects from templates, and then edit, preview and deploy your apps with a unique link.
While the core features of pyscript.com will always be free, additional paid-for capabilities directly support and sustain the PyScript open source project. Commercial and educational support is also available.
"},{"location":"beginning-pyscript/#an-application","title":"An application","text":"All PyScript applications need three things:
index.html
file that is served to your browser.pyscript.json
or pyscript.toml
file.main.py
) that defines how your application works.Create these files with your favourite code editor on your local file system. Alternatively, pyscript.com will take away all the pain of organising, previewing and deploying your application.
If you're using your local file system, you'll need a way to view your application in your browser. If you already have Python installed on your local machine, serve your files with the following command run from your terminal and in the same directory as your files:
python3 -m http.server\n
Point your browser at http://localhost:8000. Remember to refresh the page (CTRL-R
) to see any updates you may have made.
Note
If you're using VSCode as your editor, the Live Server extension can be used to reload the page as you edit your files.
Alternatively, if you have an account on GitHub you could use VSCode in your browser as a PyScript aware \"CodeSpace\" (just follow the instructions in the README file).
If you decide to use pyscript.com (recommended for first steps), once signed in, create a new project by pressing the \"+\" button on the left hand side below the site's logo. You'll be presented with a page containing three columns (listing your files, showing your code and previewing the app). The \"save\" and \"run\" buttons do exactly what you'd expect.
Let's build a simple PyScript application that translates English \ud83c\uddec\ud83c\udde7 into Pirate \ud83c\udff4\u200d\u2620\ufe0f speak. In order to do this we'll make use of the arrr library. By building this app you'll be introduced to all the core concepts of PyScript at an introductory level.
You can see this application embedded into the page below (try it out!):
Let's explore each of the three files that make this app work.
"},{"location":"beginning-pyscript/#pyscriptjson","title":"pyscript.json","text":"This file tells PyScript and your browser about various configurable aspects of your application. Put simply, it tells PyScript what it needs in order to run your application. The only thing we need to show is that we require the third party arrr
module to do the actual translation.
We do this by putting arrr
as the single entry in a list of required packages
, so the content of pyscript.json
looks like this:
{\n\"packages\": [\"arrr\"]\n}\n
"},{"location":"beginning-pyscript/#indexhtml","title":"index.html","text":"Next we come to the index.html
file that is first served to your browser.
To start out, we need to tell the browser that this HTML document uses PyScript, and so we create a <script>
tag that references the PyScript module in the document's <head>
tag:
<!DOCTYPE html>\n<html>\n<head>\n<meta charset=\"utf-8\" />\n<meta name=\"viewport\" content=\"width=device-width,initial-scale=1\" />\n<title>\ud83e\udd9c Polyglot - Piratical PyScript</title>\n<link rel=\"stylesheet\" href=\"https://pyscript.net/releases/2024.9.1/core.css\">\n<script type=\"module\" src=\"https://pyscript.net/releases/2024.9.1/core.js\"></script>\n</head>\n<body>\n<!-- TODO: Fill in our custom application code here... -->\n</body>\n</html>\n
Notice that the <body>
of the document is empty except for the TODO comment. It's in here that we put standard HTML content to define our user interface, so the <body>
now looks like:
<body>\n<h1>Polyglot \ud83e\udd9c \ud83d\udcac \ud83c\uddec\ud83c\udde7 \u27a1\ufe0f \ud83c\udff4\u200d\u2620\ufe0f</h1>\n<p>Translate English into Pirate speak...</p>\n<input type=\"text\" name=\"english\" id=\"english\" placeholder=\"Type English here...\" />\n<button py-click=\"translate_english\">Translate</button>\n<div id=\"output\"></div>\n<script type=\"py\" src=\"./main.py\" config=\"./pyscript.json\"></script>\n</body>\n
This fragment of HTML contains the application's header (<h1>
), some instructions between the <p>
tags, an <input>
box for the English text, and a <button>
to click to generate the translation. Towards the end there's a <div id=\"output\">
which will contain the resulting pirate speak as the application's output.
There's something strange about the <button>
tag: it has a py-click
attribute with the value translate_english
. This is, in fact, the name of a Python function we'll run whenever the button is clicked. Such py-*
style attributes are built into PyScript.
We put all this together in the script
tag at the end of the <body>
. This tells the browser we're using PyScript (type=\"py\"
), and where PyScript should find the Python source code (src=\"./main.py\"
). Finally, we indicate where PyScript should find the configuration (config=\"./pyscript.json\"
).
In the end, our HTML should look like this:
index.html<!DOCTYPE html>\n<html>\n<head>\n<meta charset=\"utf-8\" />\n<meta name=\"viewport\" content=\"width=device-width,initial-scale=1\" />\n<title>\ud83e\udd9c Polyglot - Piratical PyScript</title>\n<link rel=\"stylesheet\" href=\"https://pyscript.net/releases/2024.9.1/core.css\">\n<script type=\"module\" src=\"https://pyscript.net/releases/2024.9.1/core.js\"></script>\n</head>\n<body>\n<h1>Polyglot \ud83e\udd9c \ud83d\udcac \ud83c\uddec\ud83c\udde7 \u27a1\ufe0f \ud83c\udff4\u200d\u2620\ufe0f</h1>\n<p>Translate English into Pirate speak...</p>\n<input type=\"text\" id=\"english\" placeholder=\"Type English here...\" />\n<button py-click=\"translate_english\">Translate</button>\n<div id=\"output\"></div>\n<script type=\"py\" src=\"./main.py\" config=\"./pyscript.json\"></script>\n</body>\n</html>\n
But this only defines how the user interface should look. To define its behaviour we need to write some Python. Specifically, we need to define the translate_english
function, used when the button is clicked.
The behaviour of the application is defined in main.py
. It looks like this:
import arrr\nfrom pyscript import document\ndef translate_english(event):\ninput_text = document.querySelector(\"#english\")\nenglish = input_text.value\noutput_div = document.querySelector(\"#output\")\noutput_div.innerText = arrr.translate(english)\n
It's not very complicated Python code.
On line 1 the arrr
module is imported so we can do the actual English to Pirate translation. If we hadn't told PyScript to download the arrr
module in our pyscript.json
configuration file, this line would cause an error. PyScript has ensured our environment is set up with the expected arrr
module.
Line 2 imports the document
object. The document
allows us to reach into the things on the web page defined in index.html
.
Finally, on line 5 the translate_english
function is defined.
The translate_english
function takes a single parameter called event
. This represents the user's click of the button (but which we don't actually use).
Inside the body of the function we first get a reference to the input
element with the document.querySelector
function that takes #english
as its parameter (indicating we want the element with the id \"english\"). We assign the result to input_text
, then extract the user's english
from the input_text
's value
. Next, we get a reference called output_div
that points to the div
element with the id \"output\". Finally, we assign the innerText
of the output_div
to the result of calling arrr.translate
(to actually translate the english
to something piratical).
That's it!
"},{"location":"beginning-pyscript/#sharing-your-app","title":"Sharing your app","text":""},{"location":"beginning-pyscript/#pyscriptcom","title":"PyScript.com","text":"If you're using pyscript.com, you should save all your files and click the \"run\" button. Assuming you've copied the code properly, you should have a fine old time using \"Polyglot \ud83e\udd9c\" to translate English to Pirate-ish.
Alternatively, click here to see a working example of this app. Notice that the bottom right hand corner contains a link to view the code on pyscript.com. Why not explore the code, copy it to your own account and change it to your satisfaction?
"},{"location":"beginning-pyscript/#from-a-web-server","title":"From a web server","text":"Just host the three files (pyscript.json
, index.html
and main.py
) in the same directory on a static web server somewhere.
Clearly, we recommend you use pyscript.com for this, but any static web host will do (for example, GitHub Pages, Amazon's S3, Google Cloud or Microsoft's Azure).
"},{"location":"beginning-pyscript/#run-pyscript-offline","title":"Run PyScript Offline","text":"To run PyScript offline, without the need of a CDN or internet connection, read the Run PyScript Offline section of the user guide.
"},{"location":"beginning-pyscript/#conclusion","title":"Conclusion","text":"Congratulations!
You have just created your first PyScript app. We've explored the core concepts needed to build yet more interesting things of your own.
PyScript is extremely powerful, and these beginner steps only just scratch the surface. To learn about PyScript in more depth, check out our user guide or explore our example applications.
"},{"location":"conduct/","title":"Code of Conduct","text":"Our code of conduct is based on the Contributor Covenant code of conduct.
"},{"location":"conduct/#our-pledge","title":"Our Pledge","text":"We as members, contributors, and leaders pledge to make participation in our community a harassment-free experience for everyone, regardless of age, body size, visible or invisible disability, ethnicity, sex characteristics, gender identity and expression, level of experience, education, socio-economic status, nationality, personal appearance, race, religion, or sexual identity and orientation.
We pledge to act and interact in ways that contribute to an open, welcoming, diverse, inclusive, and healthy community.
"},{"location":"conduct/#our-standards","title":"Our Standards","text":"Examples of behavior that contributes to a positive environment for our community include:
Examples of unacceptable behavior include:
Community leaders are responsible for clarifying and enforcing our standards of acceptable behavior and will take appropriate and fair corrective action in response to any behavior that they deem inappropriate, threatening, offensive, or harmful.
Community leaders have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, and will communicate reasons for moderation decisions when appropriate.
"},{"location":"conduct/#scope","title":"Scope","text":"This Code of Conduct applies within all community spaces, and also applies when an individual is officially representing the community in public spaces. Examples of representing our community include using an official e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event.
"},{"location":"conduct/#enforcement","title":"Enforcement","text":"Instances of abusive, harassing, or otherwise unacceptable behavior may be reported to the community leaders responsible for enforcement as set forth in the repository's Notice.md file. All complaints will be reviewed and investigated promptly and fairly.
All community leaders are obligated to respect the privacy and security of the reporter of any incident.
"},{"location":"conduct/#enforcement-guidelines","title":"Enforcement Guidelines","text":"Community leaders will follow these Community Impact Guidelines in determining the consequences for any action they deem in violation of this Code of Conduct:
"},{"location":"conduct/#1-correction","title":"1. Correction","text":"Community Impact: Use of inappropriate language or other behavior deemed unprofessional or unwelcome in the community.
Consequence: A private, written warning from community leaders, providing clarity around the nature of the violation and an explanation of why the behavior was inappropriate. A public apology may be requested.
"},{"location":"conduct/#2-warning","title":"2. Warning","text":"Community Impact: A violation through a single incident or series of actions.
Consequence: A warning with consequences for continued behavior. No interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, for a specified period of time. This includes avoiding interactions in community spaces as well as external channels like social media. Violating these terms may lead to a temporary or permanent ban.
"},{"location":"conduct/#3-temporary-ban","title":"3. Temporary Ban","text":"Community Impact: A serious violation of community standards, including sustained inappropriate behavior.
Consequence: A temporary ban from any sort of interaction or public communication with the community for a specified period of time. No public or private interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, is allowed during this period. Violating these terms may lead to a permanent ban.
"},{"location":"conduct/#4-permanent-ban","title":"4. Permanent Ban","text":"Community Impact: Demonstrating a pattern of violation of community standards, including sustained inappropriate behavior, harassment of an individual, or aggression toward or disparagement of classes of individuals.
Consequence: A permanent ban from any sort of public interaction within the project community.
"},{"location":"conduct/#reporting-a-violation","title":"Reporting a violation","text":"To report a violation of the Code of Conduct, e-mail conduct@pyscript.net
"},{"location":"conduct/#attribution","title":"Attribution","text":"This Code of Conduct is adapted from the Contributor Covenant, version 2.0, available at https://www.contributor-covenant.org/version/2/0/code_of_conduct.html.
Community Impact Guidelines were inspired by Mozilla's code of conduct enforcement ladder.
For answers to common questions about this code of conduct, see the FAQ at https://www.contributor-covenant.org/faq. Translations are available at https://www.contributor-covenant.org/translations.
"},{"location":"contributing/","title":"Contributing","text":"Thank you for wanting to contribute to the PyScript project!
"},{"location":"contributing/#code-of-conduct","title":"Code of conduct","text":"The PyScript Code of Conduct governs the project and everyone participating in it. By participating, you are expected to uphold this code. Please report unacceptable behavior to the maintainers or administrators as described in that document.
"},{"location":"contributing/#ways-to-contribute","title":"Ways to contribute","text":""},{"location":"contributing/#report-bugs","title":"Report bugs","text":"Bugs are tracked on the project issues page.
Check first
Please check your bug has not already been reported by someone else by searching the existing issues before filing a new one. Once your issue is filed, it will be triaged by another contributor or maintainer. If there are questions raised about your issue, please respond promptly.
If it is not appropriate to submit a security issue using the above process, please e-mail us at security@pyscript.net.
"},{"location":"contributing/#ask-questions","title":"Ask questions","text":"If you have questions about the project, using PyScript, or anything else, please ask in the project's discord server.
"},{"location":"contributing/#create-resources","title":"Create resources","text":"Folks make all sorts of wonderful things with PyScript.
If you have an interesting project, a cool hack, or an innovative way to implement a new capability or feature, please share your work and tell us about it so we can celebrate and amplify your contribution.
Please reach out to us if you'd like advice and feedback.
"},{"location":"contributing/#participate","title":"Participate","text":"As an open source project, PyScript has community at its core. In addition to the ways to engage already outlined, you could join our live community calls.
Announcement of connection details is made via the PyScript discord server.
"},{"location":"contributing/#technical-contributions","title":"Technical contributions","text":"In addition to working with PyScript, if you would like to contribute to PyScript itself, the following advice should be followed.
"},{"location":"contributing/#places-to-start","title":"Places to start","text":"If you're not sure where to begin, we have some suggestions:
We assume you are familiar with core development practices such as using a code editor, writing Python and/or JavaScript and working with tools and services such as GIT and GitHub.
git clone https://github.com/<your username>/pyscript\n
upstream
.git remote add upstream https://github.com/pyscript/pyscript.git\n
git pull upstream main\n
PyScrcipt welcomes contributions, suggestions, and feedback. All contributions, suggestions, and feedback you submitted are accepted under the Apache 2.0 license. You represent that if you do not own copyright in the code that you have the authority to submit it under the Apache 2.0 license. All feedback, suggestions, or contributions are not confidential.
"},{"location":"contributing/#becoming-a-maintainer","title":"Becoming a maintainer","text":"Contributors are invited to be maintainers of the project by demonstrating good decision making in their contributions, a commitment to the goals of the project, and consistent adherence to the code of conduct. New maintainers are invited by a 3/4 vote of the existing maintainers.
"},{"location":"contributing/#trademarks","title":"Trademarks","text":"The Project abides by the Organization's trademark policy.
"},{"location":"developers/","title":"Developer Guide","text":"This page explains the technical and practical requirements and processes needed to contribute to PyScript.
Info
In the following instructions, we assume familiarity with git
, GitHub, the command line and other common development concepts, tools and practices.
For those who come from a non-Pythonic technical background (for example, you're a JavaScript developer), we will explain Python-isms as we go along so you're contributing with confidence.
If you're unsure, or encounter problems, please ask for help on our discord server.
"},{"location":"developers/#welcome","title":"Welcome","text":"We are a diverse, inclusive coding community and welcome contributions from anyone irrespective of their background. If you're thinking, \"but they don't mean me\", then we especially mean YOU. Our diversity means you will meet folks in our community who are different to yourself. Therefore, thoughtful contributions made in good faith, and engagement with respect, care and compassion wins every time.
All contributors are expected to follow our code of conduct.
"},{"location":"developers/#setup","title":"Setup","text":"You must have recent versions of Python, node.js and npm already installed on your system.
The following steps create a working development environment for PyScript. It is through this environment that you contribute to PyScript.
Danger
The following commands work on Unix like operating systems (like MacOS or Linux). If you are a Microsoft Windows user please use the Windows Subsystem for Linux with the following instructions.
"},{"location":"developers/#create-a-virtual-environment","title":"Create a virtual environment","text":"A Python virtual environment is a computing \"sandbox\" that safely isolates your work. PyScript's development makes use of various Python based tools, so both Python and a virtual environment is needed. There are many tools to help manage these environments, but the standard way to create a virtual environment is to use this command in your terminal:
python3 -m venv my_pyscript_dev_venv\n
Warning
Replace my_pyscript_dev_venv
with a meaningful name for the virtual environment, that works for you.
A my_pyscript_dev_venv
directory containing the virtual environment's \"stuff\" is created as a subdirectory of your current directory. Next, activate the virtual environment to ensure your development activities happen within the context of the sandbox:
source my_pyscript_dev_venv/bin/activate\n
The prompt in your terminal will change to include the name of your virtual environment indicating the sandbox is active. To deactivate the virtual environment just type the following into your terminal:
deactivate\n
Info
The rest of the instructions on this page assume you are working in an activated virtual environment for developing PyScript.
"},{"location":"developers/#prepare-your-repository","title":"Prepare your repository","text":"Clone your newly forked version of the PyScript repository onto your local development machine. For example, use this command in your terminal:
git clone https://github.com/<YOUR USERNAME>/pyscript\n
Warning
In the URL for the forked PyScript repository, remember to replace <YOUR USERNAME>
with your actual GitHub username.
Tip
To help explain steps, we will use git
commands to be typed into your terminal / command line.
The equivalent of these commands could be achieved through other means (such as GitHub's desktop client). How these alternatives work is beyond the scope of this document.
Change into the root directory of your newly cloned pyscript
repository:
cd pyscript\n
Add the original PyScript repository as your upstream
to allow you to keep your own fork up-to-date with the latest changes:
git remote add upstream https://github.com/pyscript/pyscript.git\n
If the above fails, try this alternative:
git remote remove upstream\ngit remote add upstream git@github.com:pyscript/pyscript.git\n
Pull in the latest changes from the main upstream
PyScript repository:
git pull upstream main\n
Pyscript uses a Makefile
to automate the most common development tasks. In your terminal, type make
to see what it can do. You should see something like this:
There is no default Makefile target right now. Try:\n\nmake setup - check your environment and install the dependencies.\nmake clean - clean up auto-generated assets.\nmake build - build PyScript.\nmake precommit-check - run the precommit checks (run eslint).\nmake test-integration - run all integration tests sequentially.\nmake fmt - format the code.\nmake fmt-check - check the code formatting.\n
To install the required software dependencies for working on PyScript, in your terminal type:
make setup\n
Updates from npm
and then pip
will scroll past telling you about their progress installing the required packages.
Warning
The setup
process checks the versions of Python, node and npm. If you encounter a failure at this point, it's probably because one of these pre-requisits is out of date on your system. Please update!
To ensure consistency of code layout we use tools to both reformat and check the code.
To ensure your code is formatted correctly:
make fmt\n
To check your code is formatted correctly:
make fmt-check\n
Finally, as part of the automated workflow for contributing pull requests pre-commit checks the source code. If this fails revise your PR. To run pre-commit checks locally (before creating the PR):
make precommit-check\n
This may also revise your code formatting. Re-run make precommit-check
to ensure this is the case.
To turn the JavaScript source code found in the pyscript.core
directory into a bundled up module ready for the browser, type:
make build\n
The resulting assets will be in the pyscript.core/dist
directory.
The integration tests for PyScript are started with:
make test-integration\n
Documentation for PyScript (i.e. what you're reading right now), is found in a separate repository: https://github.com/pyscript/docs
The documentation's README
file contains instructions for setting up a development environment and contributing.
We have suggestions for how to contribute to PyScript. Take a read and dive in.
Please make sure you discuss potential contributions before you put in work. We don#t want folks to waste their time or re-invent the wheel.
Technical discussions happen on our discord server and in the discussions section of our GitHub repository.
Every Tuesday is a technical community video call, the details of which are posted onto the discord server. Face to face technical discussions happen here.
Every Wednesday is a non-technical community engagement call, in which we organise how to engage with, grow and nourish our community.
Every two weeks, on a Thursday, is a PyScript FUN call, the details of which are also posted to discord. Project show-and-tells, cool hacks, new features and a generally humorous and creative time is had by all.
A curated list of example applications that demonstrate various features of PyScript can be found on PyScript.com.
The examples are (links take you to the code):
This page contains the most common questions and \"gotchas\" asked on our Discord server, in our community calls, or within our community.
There are two major areas we'd like to explore: common errors and helpful hints.
"},{"location":"faq/#common-errors","title":"Common errors","text":""},{"location":"faq/#reading-errors","title":"Reading errors","text":"If your application doesn't run, and you don't see any error messages on the page, you should check your browser's console.
When reading an error message, the easy way to find out what's going on, most of the time, is to read the last line of the error.
A Pyodide error.Traceback (most recent call last):\n File \"/lib/python311.zip/_pyodide/_base.py\", line 501, in eval_code\n .run(globals, locals)\n ^^^^^^^^^^^^^^^^^^^^\n File \"/lib/python311.zip/_pyodide/_base.py\", line 339, in run\n coroutine = eval(self.code, globals, locals)\n ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n File \"<exec>\", line 1, in <module>\nNameError: name 'failure' is not defined\n\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\n
A MicroPython error.Traceback (most recent call last):\n File \"<stdin>\", line 1, in <module>\nNameError: name 'failure' isn't defined\n\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\n
In both examples, the code created a NameError
because the object with the name failure
did not exist. Everything above the error message is potentially useful technical detail.
With this context in mind, these are the most common errors users of PyScript encounter.
"},{"location":"faq/#sharedarraybuffer","title":"SharedArrayBuffer","text":"This is the first and most common error users may encounter with PyScript:
Failure
Your application doesn't run and in your browser's console you see this message:
Unable to use `window` or `document` -> https://docs.pyscript.net/latest/faq/#sharedarraybuffer\n
"},{"location":"faq/#when","title":"When","text":"This happens when you're unable to access objects in the main thread (window
and document
) from code running in a web worker.
This error happens because the server delivering your PyScript application is incorrectly configured or a service-worker
attribute has not been used in your script
element.
Specifically, one of the following three problem situations applies to your code:
worker
attribute in your script
element, and your Python code uses the window
or document
objects (that actually exist on the main thread), then the browser limitation on Atomics will cause the failure, unless you reconfigure your server.<script type=\"py-editor\">
(that must always use a worker behind the scenes) and no fallback has been provided via a service-worker
attribute on that element.PyWorker
or MPWorker
instance bootstrapping somewhere in your code and no service_worker
fallback has been provided.All these cases have been documented with code examples and possible solutions in our section on web workers.
"},{"location":"faq/#why","title":"Why","text":"The only way for document.getElementById('some-id').value
to work in a worker is to use these two JavaScript primitives:
wait(sab, index)
(sab
is a SharedArrayBuffer
) and notify(sab, index)
to unlock the awaiting thread.While a worker waits for an operation on main to happen, it is not using the CPU. It idles until the referenced index of the shared buffer changes, effectively never blocking the main thread while still pausing its own execution until the buffer's index is changed.
As overwhelming or complicated as this might sound, these two fundamental primitives make main \u2194 worker interoperability an absolute wonder in term of developer experience. Therefore, we encourage folks to prefer using workers over running Python in the main thread. This is especially so when using Pyodide related projects, because of its heavier bootstrap or computation requirements. Using workers ensures the main thread (and thus, the user interface) remains unblocked.
Unfortunately, we can patch, polyfill, or workaround, these primitives but we cannot change their intrinsic nature and limitations defined by web standards. However, there are various solutions for working around such limitations. Please read our web workers section to learn more.
"},{"location":"faq/#borrowed-proxy","title":"Borrowed proxy","text":"This is another common error that happens with listeners, timers or in any other situation where a Python callback is lazily invoked from JavaScript:
Failure
Your application doesn't run and in your browser's console you see this message:
Uncaught Error: This borrowed proxy was automatically destroyed at the end of a function call.\nTry using create_proxy or create_once_callable.\nFor more information about the cause of this error, use `pyodide.setDebug(true)`\n
"},{"location":"faq/#when_1","title":"When","text":"This error happens when using Pyodide as the interpreter on the main thread, and when a bare Python callable/function has been passed into JavaScript as a callback handler:
An expired borrowed proxy example, with Pyodide on the main thread.import js\n# will throw the error\njs.setTimeout(lambda msg: print(msg), 1000, \"FAIL\")\n
The garbage collector immediately cleans up the Python function once it is passed into the JavaScript context. Clearly, for the Python function to work as a callback at some time in the future, it should NOT be garbage collected and hence the error message.
Info
This error does not happen if the code is executed in a worker and the JavaScript reference comes from the main thread:
Code running on Pyodide in a worker has no borrowed proxy issue.from pyscript import window\nwindow.setTimeout(lambda x: print(x), 1000, \"OK\")\n
Proxy objects (i.e. how Python objects appear to JavaScript, and vice versa) cannot be communicated between a worker and the main thread.
Behind the scenes, PyScript ensures references are maintained between workers and the main thread. It means Python functions in a worker are actually represented by JavaScript proxy objects in the main thread.
As a result, such worker based Python functions are therefore not bare Python functions, but already wrapped in a managed JavaScript proxy, thus avoiding the borrowed proxy problem.
If you encounter this problem you have two possible solutions:
pyscript.ffi.create_proxy
.experimental_create_proxy = \"auto\"
flag in your application's settings. This flag intercepts Python objects passed into a JavaScript callback and ensures an automatic and sensible memory management operation via the JavaScript garbage collector.Note
The FinalizationRegistry is the browser feature used to make this so.
By default, it is not observable and it is not possible to predict when it will free, and hence destroy, retained Python proxy objects. As a result, memory consumption might be slightly higher than when manually using create_proxy
. However, the JavaScript engine is responsible for memory consumption, and will cause the finalization registry to free all retained proxies, should memory consumption become too high.
PyScript's interpreters (Pyodide and MicroPython) both have their own garbage collector for automatic memory management. When references to Python objects are passed to JavaScript via the FFI, the Python interpreters cannot guarantee such references will ever be freed by JavaScript's own garbage collector. They may even lose control over the reference since there's no infallible way to know when such objects won't be needed by JavaScript.
One solution is to expect users to explicitly create and destroy such proxy objects themselves. But this manual memory management makes automatic memory management pointless while raising the possibility of dead references (where the user explicitly destroys a Python object that's still alive in the JavaScript context). Put simply, this is a difficult situation.
Pyodide provides ffi.wrappers to help with many of the common cases, and PyScript, through the experimental_create_proxy = \"auto\"
configuration option, automates memory management via the FinalizationRegistry
described above.
Sometimes Python packages, specified via the packages
configuration setting don't work with PyScript's Python interpreter.
Failure
You are using Pyodide.
Your application doesn't run and in your browser's console you see this message:
ValueError: Can't find a pure Python 3 wheel for: 'package_name'\n
Failure
You are using MicroPython.
Your application doesn't run and in your browser's console you see this message:
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the\nremote resource at https://micropython.org/pi/v2/package/py/package_name/latest.json.\n(Reason: CORS header \u2018Access-Control-Allow-Origin\u2019 missing).\nStatus code: 404.\n
"},{"location":"faq/#when_2","title":"When","text":"This is a complicated problem, but the summary is:
micropython-lib
package repository. If you want to use a pure Python package with MicroPython, use the files configuration option to manually copy the package onto the file system, or use a URL to reference the package.For hints and tips about packaging related aspects of PyScript read the packaging pointers section of this FAQ.
"},{"location":"faq/#why_2","title":"Why","text":"Put simply, Pyodide and MicroPython are different Python interpreters, and both are running in a web assembly environment. Packages built for Pyodide may not work for MicroPython, and vice versa. Furthermore, if a package contains compiled code, it may not yet have been natively compiled for web assembly.
If the package you want to use is written in a version of Python that both Pyodide and MicroPython support (there are subtle differences between the interpreters), then you should be able to use the package so long as you are able to get it into the Python path via configuration (see above).
Currently, MicroPython cannot expose modules that require native compilation, but PyScript is working with the MicroPython team to provide different builds of MicroPython that include commonly requested packages (e.g. MicroPython's version of numpy
or sqlite
).
Warning
Depending on the complexity of the project, it may be hard to seamlessly make a 1:1 port from a Pyodide code base to MicroPython.
MicroPython has comprehensive documentation to explain the differences between itself and \"regular\" CPython (i.e. the version of Python Pyodide provides).
"},{"location":"faq/#javascript-modules","title":"JavaScript modules","text":"When using JavaScript modules with PyScript you may encounter the following errors:
Failure
Uncaught SyntaxError: The requested module './library.js' does not provide an export named 'default'
Failure
Uncaught SyntaxError: The requested module './library.js' does not provide an export named 'util'
"},{"location":"faq/#when_3","title":"When","text":"These errors happen because the JavaScript module you are trying to use is not written as a standards-compliant JavaScript module.
Happily, to solve this issue various content delivery networks (CDNs) provide a way to automatically deliver standard ESM (aka: ECMAScript Modules). The one we recommend is esm.run.
An example of esm.run<mpy-config>\n[js_modules.main]\n\"https://esm.run/d3\" = \"d3\"\n</mpy-config>\n<script type=\"mpy\">\nfrom pyscript.js_modules import d3\n</script>\n
Alternatively, ensure any JavaScript code you reference uses export ...
or ask for an .mjs
version of the code. All the various options and technical considerations surrounding the use of JavaScript modules in PyScript are covered in our user guide.
Even though the standard for JavaScript modules has existed since 2015, many old and new libraries still produce files that are incompatible with such modern and idiomatic standards.
This isn't so much a technical problem, as a human problem as folks learn to use the new standard and migrate old code away from previous and now obsolete standards.
While such legacy code exists, be aware that JavaScript code may require special care.
"},{"location":"faq/#possible-deadlock","title":"Possible deadlock","text":"Users may encounter an error message similar to the following:
Failure
\ud83d\udc80\ud83d\udd12 - Possible deadlock if proxy.xyz(...args) is awaited\n
"},{"location":"faq/#when_4","title":"When","text":"This error happens when your code on a worker and in the main thread are in a deadlock. Put simply, neither fragment of code can proceed without waiting for the other.
"},{"location":"faq/#why_4","title":"Why","text":"Let's assume a worker script contains the following Python code:
worker: a deadlock examplefrom pyscript import sync\nsync.worker_task = lambda: print('\ud83d\udd25 this is fine \ud83d\udd25')\n# deadlock \ud83d\udc80\ud83d\udd12\nsync.main_task()\n
On the main thread, let's instead assume this code:
main: a deadlock example<script type=\"mpy\">\nfrom pyscript import PyWorker\ndef async main_task():\n# deadlock \ud83d\udc80\ud83d\udd12\nawait pw.sync.worker_task()\npw = PyWorker(\"./worker.py\", {\"type\": \"pyodide\"})\npw.sync.main_task = main_task\n</script>\n
When the worker bootstraps and calls sync.main_task()
on the main thread, it blocks until the result of this call is returned. Hence it cannot respond to anything at all. However, in the code on the main thread, the sync.worker_task()
in the worker is called, but the worker is blocked! Now the code on both the main thread and worker are mutually blocked and waiting on each other. We are in a classic deadlock situation.
The moral of the story? Don't create such circular deadlocks!
How?
The mutually blocking calls cause the deadlock, so simply don't block.
For example, on the main thread, let's instead assume this code:
main: avoiding deadlocks<script type=\"mpy\">\nfrom pyscript import window, PyWorker\nasync def main_task():\n# do not await the worker,\n# just schedule it for later (as resolved)\nwindow.Promise.resolve(pw.sync.worker_task())\npw = PyWorker(\"./worker.py\", {\"type\": \"pyodide\"})\npw.sync.main_task = main_task\n</script>\n
By scheduling the call to the worker (rather than awaiting it), it's possible for the main thread to call functions defined in the worker in a non-blocking manner, thus allowing the worker to also work in an unblocked manner and react to such calls. We have resolved the mutual deadlock.
"},{"location":"faq/#helpful-hints","title":"Helpful hints","text":"This section contains common hacks or hints to make using PyScript easier.
Note
We have an absolutely lovely PyScript contributor called Jeff Glass who maintains an exceptional blog full of PyScript recipes with even more use cases, hints, tips and solutions. Jeff also has a wonderful YouTube channel full of very engaging PyScript related content.
If you cannot find what you are looking for here, please check Jeff's blog as it's likely he's probably covered something close to the situation in which you find yourself.
Of course, if ever you meet Jeff in person, please buy him a beer and remember to say a big \"thank you\". \ud83c\udf7b
"},{"location":"faq/#pyscript-latest","title":"PyScriptlatest
","text":"PyScript follows the CalVer convention for version numbering.
Put simply, it means each version is numbered according to when, in the calendar, it was released. For instance, version 2024.4.2
was the second release in the month of April in the year 2024 (not the release on the 2nd of April but the second release in April).
It used to be possible to reference PyScript via a version called latest
, which would guarantee you always got the latest release.
However, at the end of 2023, we decided to stop supporting latest
as a way to reference PyScript. We did this for two broad reasons:
latest
, found their applications broke. We want to avoid this at all costs.Therefore, pinning your app's version of PyScript to a specific release (rather than latest
) ensures you get exactly the version of PyScript you used when writing your code.
However, as we continue to develop PyScript it is possible to get our latest development version of PyScript via npm
and we could (should there be enough interest) deliver our work-in-progress via a CDN's \"canary\" or \"development\" channel. We do not guarantee the stability of such versions of PyScript, so never use them in production, and our documentation may not reflect the development version.
If you require the development version of PyScript, these are the URLs to use:
PyScript development. \u26a0\ufe0f\u26a0\ufe0f\u26a0\ufe0f WARNING: HANDLE WITH CARE! \u26a0\ufe0f\u26a0\ufe0f\u26a0\ufe0f<link rel=\"stylesheet\" href=\"https://cdn.jsdelivr.net/npm/@pyscript/core/dist/core.css\">\n<script type=\"module\" src=\"https://cdn.jsdelivr.net/npm/@pyscript/core/dist/core.js\"></script>\n
Warning
Do not use shorter urls or other CDNs.
PyScript needs both the correct headers to use workers and to find its own assets at runtime. Other CDN links might result into a broken experience.
"},{"location":"faq/#workers-via-javascript","title":"Workers via JavaScript","text":"Sometimes you want to start a Pyodide or MicroPython web worker from JavaScript.
Here's how:
Starting a PyScript worker from JavaScript.<script type=\"module\">\n// use sourceMap for @pyscript/core or change to a CDN\nimport {\nPyWorker, // Pyodide Worker\nMPWorker // MicroPython Worker\n} from '@pyscript/core';\nconst worker = await MPWorker(\n// Python code to execute\n'./micro.py',\n// optional details or config with flags\n{ config: { sync_main_only: true } }\n// ^ just as example ^\n);\n// \"heavy computation\"\nawait worker.sync.doStuff();\n// kill the worker when/if needed\nworker.terminate();\n</script>\n
micro.pyfrom pyscript import sync\ndef do_stuff():\nprint(\"heavy computation\")\n# Note: this reference is awaited in the JavaScript code.\nsync.doStuff = do_stuff\n
"},{"location":"faq/#javascript-classnew","title":"JavaScript Class.new()
","text":"When using Python to instantiate a class defined in JavaScript, one needs to use the class's new()
method, rather than just using Class()
(as in Python).
Why?
The reason is technical, related to JavaScript's history and its relatively poor introspection capabilities:
typeof function () {}
and typeof class {}
produce the same outcome: function
. This makes it very hard to disambiguate the intent of the caller as both are valid, JavaScript used to use function
(rather than class
) to instantiate objects, and the class you're using may not use the modern, class
based, idiom.apply
and construct
methods used during instantiation. However, because of the previous point, it's not possible to be sure that apply
is meant to construct
an instance or call a function.Class()
in JavaScript (without the new
operator) throws an error.new Class()
is invalid syntax in Python. So there is still a need to somehow disambiguate the intent to call a function or instantiate a class.Class.new()
to explicitly signal the intent to instantiate a JavaScript class. While not ideal it is clear and unambiguous.PyScript uses hooks during the lifecycle of the application to facilitate the creation of plugins.
Beside hooks, PyScript also dispatches events at specific moments in the lifecycle of the app, so users can react to changes in state:
"},{"location":"faq/#mpyready","title":"m/py:ready","text":"Both the mpy:ready
and py:ready
events are dispatched for every PyScript related element found on the page. This includes <script type=\"py\">
, <py-script>
or any MicroPython/mpy
counterpart.
The m/py:ready
events dispatch immediately before the code is executed, but after the interpreter is bootstrapped.
<script>\naddEventListener(\"py:ready\", () => {\n// show running for an instance\nconst status = document.getElementById(\"status\");\nstatus.textContent = 'running';\n});\n</script>\n<!-- show bootstrapping right away -->\n<div id=\"status\">bootstrapping</div>\n<script type=\"py\" worker>\nfrom pyscript import document\n# show done after running\nstatus = document.getElementById(\"status\")\nstatus.textContent = \"done\"\n</script>\n
A classic use case for this event is to recreate the \"starting up\" spinner that used to be displayed when PyScript bootstrapped. Just show the spinner first, then close it once py:ready
is triggered!
Warning
If using Pyodide on the main thread, the UI will block until Pyodide has finished bootstrapping. The \"starting up\" spinner won't work unless Pyodide is started on a worker instead.
"},{"location":"faq/#mpydone","title":"m/py:done","text":"The mpy:done
and py:done
events dispatch after the either the synchronous or asynchronous code has finished execution.
<script>\naddEventListener(\"py:ready\", () => {\n// show running for an instance\nconst status = document.getElementById(\"status\");\nstatus.textContent = 'running';\n});\naddEventListener(\"py:done\", () => {\n// show done after logging \"Hello \ud83d\udc4b\"\nconst status = document.getElementById(\"status\");\nstatus.textContent = 'done';\n});\n</script>\n<!-- show bootstrapping right away -->\n<div id=\"status\">bootstrapping</div>\n<script type=\"py\" worker>\nprint(\"Hello \ud83d\udc4b\")\n</script>\n
Warning
If async
code contains an infinite loop or some orchestration that keeps it running forever, then these events may never trigger because the code never really finishes.
The py:all-done
event dispatches when all code is finished executing.
This event is special because it depends upon all the MicroPython and Pyodide scripts found on the page, no matter the interpreter.
In this example, MicroPython waves before Pyodide before the \"everything is done\"
message is written to the browser's console.
<script>\naddEventListener(\"py:all-done\", () => {\nconsole.log(\"everything is done\");\n});\n</script>\n<script type=\"mpy\" worker>\nprint(\"MicroPython \ud83d\udc4b\")\n</script>\n<script type=\"py\" worker>\nprint(\"Pyodide \ud83d\udc4b\")\n</script>\n
"},{"location":"faq/#mpyprogress","title":"m/py:progress","text":"The py:progress
or mpy:progress
event triggers on the main thread during interpreter bootstrap (no matter if your code is running on main or in a worker).
The received event.detail
is a string that indicates operations between Loading {what}
and Loaded {what}
. So, the first event would be, for example, Loading Pyodide
and the last one per each bootstrap would be Loaded Pyodide
.
In between all operations are event.detail
s, such as:
Loading files
and Loaded files
, when [files]
is found in the optional configLoading fetch
and Loaded fetch
, when [fetch]
is found in the optional configLoading JS modules
and Loaded JS modules
, when [js_modules.main]
or [js_modules.worker]
is found in the optional configLoading ...
and Loaded ...
events so that users can see what is going on while PyScript is bootstrappingAn example of this listener applied to a dialog can be found in here.
"},{"location":"faq/#packaging-pointers","title":"Packaging pointers","text":"Applications need third party packages and PyScript can be configured to automatically install packages for you. Yet packaging can be a complicated beast, so here are some hints for a painless packaging experience with PyScript.
There are essentially five ways in which a third party package can become available in PyScript.
packages
setting in PyScript. There are plans for MicroPython to offer different builds for PyScript, some to include MicroPython's version of numpy or the API for sqlite.files
setting..zip
or .tgz
/.tar.gz
/.whl
archive to be decompressed into the file system (again, via the files
setting)..whl
package and reference it via a URL in the packages = [...]
list.Just put the package you need somewhere it can be served (like PyScript.com) and reference the URL in the packages
setting. So long as the server at which you are hosting the package allows CORS (fetching files from other domains) everything should just work.
It is even possible to install such packages at runtime, as this example using MicroPython's mip
tool demonstrates (the equivalent can be achieved with Pyodide via micropip
).
# Install default version from micropython-lib\nmip.install(\"keyword\")\n# Install from raw URL\nmip.install(\"https://raw.githubusercontent.com/micropython/micropython-lib/master/python-stdlib/bisect/bisect.py\")\n# Install from GitHub shortcut\nmip.install(\"github:jeffersglass/some-project/foo.py\")\n
"},{"location":"faq/#provide-your-own-file","title":"Provide your own file","text":"One can use the files
setting to copy packages onto the Python path:
<mpy-config>\n[files]\n\"./modules/bisect.py\" = \"./bisect.py\"\n</mpy-config>\n<script type=\"mpy\">\nimport bisect\n</script>\n
"},{"location":"faq/#code-archive-ziptgzwhl","title":"Code archive (zip
/tgz
/whl
)","text":"Compress all the code you want into an archive (using either either zip
or tgz
/tar.gz
). Host the resulting archive and use the files
setting to decompress it onto the Python interpreter's file system.
Consider the following file structure:
my_module/__init__.py\nmy_module/util.py\nmy_module/sub/sub_util.py\n
Host it somewhere, and decompress it into the home directory of the Python interpreter:
A code archive.<mpy-config>\n[files]\n\"./my_module.zip\" = \"./*\"\n</mpy-config>\n<script type=\"mpy\">\nfrom my_module import util\nfrom my_module.sub import sub_util\n</script>\n
Please note, the target folder must end with a star (*
), and will contain everything in the archive. For example, \"./*\"
refers to the home folder for the interpreter.
Python expects a file system. In PyScript each interpreter provides its own in-memory virtual file system. This is not the same as the filesystem on the user's device, but is simply a block of memory in the browser.
Warning
The file system is not persistent nor shareable (yet).
Every time a user loads or stores files, it is done in ephemeral memory associated with the current browser session. Beyond the life of the session, nothing is shared, nothing is stored, nothing persists!
"},{"location":"faq/#readwrite","title":"Read/Write","text":"The easiest way to add content to the virtual file system is by using native Python file operations:
Writing to a text file.with open(\"./test.txt\", \"w\") as dest:\ndest.write(\"hello vFS\")\ndest.close()\n# Read and print the written content.\nwith open(\"./test.txt\", \"r\") as f:\ncontent = f.read()\nprint(content)\n
Combined with our pyscript.fetch
utility, it's also possible to store more complex data from the web.
# Assume async execution.\nfrom pyscript import fetch, window\nhref = window.location.href\nwith open(\"./page.html\", \"wb\") as dest:\ndest.write(await fetch(href).bytearray())\n# Read and print the current HTML page.\nwith open(\"./page.html\", \"r\") as source:\nprint(source.read())\n
"},{"location":"faq/#upload","title":"Upload","text":"It's possible to upload a file onto the virtual file system from the browser (<input type=\"file\">
), and using the DOM API.
The following fragment is just one way to achieve this. It's very simple and builds on the file system examples already seen.
Upload files onto the virtual file system via the browser.<!-- Creates a file upload element on the web page. -->\n<input type=\"file\">\n<!-- Python code to handle file uploads via the HTML input element. -->\n<script type=\"mpy\">\nfrom pyscript import document, fetch, window\nasync def on_change(event):\n# For each file the user has selected to upload...\nfor file in input.files:\n# create a temporary URL,\ntmp = window.URL.createObjectURL(file)\n# fetch and save its content somewhere,\nwith open(f\"./{file.name}\", \"wb\") as dest:\ndest.write(await fetch(tmp).bytearray())\n# then revoke the tmp URL.\nwindow.URL.revokeObjectURL(tmp)\n# Grab a reference to the file upload input element and add\n# the on_change handler (defined above) to process the files.\ninput = document.querySelector(\"input[type=file]\")\ninput.onchange = on_change\n</script>\n
"},{"location":"faq/#download","title":"Download","text":"It is also possible to create a temporary link through which you can download files present on the interpreter's virtual file system.
Download file from the virtual file system.from pyscript import document, ffi, window\nimport os\ndef download_file(path, mime_type):\nname = os.path.basename(path)\nwith open(path, \"rb\") as source:\ndata = source.read()\n# Populate the buffer.\nbuffer = window.Uint8Array.new(len(data))\nfor pos, b in enumerate(data):\nbuffer[pos] = b\ndetails = ffi.to_js({\"type\": mime_type})\n# This is JS specific\nfile = window.File.new([buffer], name, details)\ntmp = window.URL.createObjectURL(file)\ndest = document.createElement(\"a\")\ndest.setAttribute(\"download\", name)\ndest.setAttribute(\"href\", tmp)\ndest.click()\n# here a timeout to window.URL.revokeObjectURL(tmp)\n# should keep the memory clear for the session\n
"},{"location":"faq/#create_proxy","title":"create_proxy","text":"The create_proxy
function is described in great detail on the FFI page, but it's also useful to explain when create_proxy
is needed and the subtle differences between Pyodide and MicroPython.
To call a Python function from JavaScript, the native Python function needs to be wrapped in a JavaScript object that JavaScript can use. This JavaScript object converts and normalises arguments passed into the function before handing off to the native Python function. It also reverses this process with any results from the Python function, and so converts and normalises values before returning the result to JavaScript.
The JavaScript primitive used for this purpose is the Proxy. It enables \"traps\", such as apply, so the extra work required to call the Python function can happen.
Once the apply(target, self, args)
trap is invoked:
self
argument for apply
is probably ignored for most common cases.args
must be resolved and converted into their Python primitive representations or associated Python objects.Ultimately, the targets referenced in the apply
must exist in the Python context so they are ready when the JavaScript apply
method calls into the Python context.
Here's the important caveat: locally scoped Python functions, or functions created at run time cannot be retained forever.
A basic Python to JavaScript callback.import js\njs.addEventListener(\n\"custom:event\",\nlambda e: print(e.type)\n)\n
In this example, the anonymous lambda
function has no reference in the Python context. It's just delegated to the JavaScript runtime via addEventListener
, and then Python immediately garbage collects it. However, as previously mentioned, such a Python object must exist for when the custom:event
is dispatched.
Furthermore, there is no way to define how long the lambda
should be kept alive in the Python environment, nor any way to discover if the custom:event
callback will ever dispatch (so the lambda
is forever pending). PyScript, the browser and the Python interpreters can only work within a finite amount of memory, so memory management and the \"aliveness\" of objects is important.
Therefore, create_proxy
is provided to delegate responsibility for the lifecycle of an object to the author of the code. In other words, wrapping the lambda
in a call to create_proxy
would ensure the Python interpreter retains a reference to the anonymous function for future use.
Info
This probably feels strange! An implementation detail of how the Python and JavaScript worlds interact with each other is bleeding into your code via create_proxy
. Surely, if we always just need to create a proxy, a more elegant solution would be to do this automatically?
As you'll see, this is a complicated situation with inevitable tradeoffs, but ultimately, through the experimental_create_proxy = \"auto\"
flag, you probably never need to use create_proxy
. This section of our docs gives you the context you need to make an informed decision.
However, this isn't the end of the story.
When a Python callback is attached to a specific JavaScript instance (rather than passed as argument into an event listener), it is easy for the Python interpreter to know when the function could be freed from the memory.
A sticky lambda.from pyscript import document\n# logs \"click\" if nothing else stopped propagation\ndocument.onclick = lambda e: print(e.type)\n
\"Wait, wat? This doesn't make sense at all!?!?\", is a valid question/response to this situation.
In this case there's no need to use create_proxy
because the JavaScript reference to which the function is attached isn't going away and the interpreter can use the FinalizationRegistry
to destroy the lambda
(or decrease its reference count) when the underlying JavaScript reference to which it is attached is itself destroyed.
The create_proxy
utility was created (among others) to smooth out and circumvent the afore mentioned memory issues when using Python callables with JavaScript event handlers.
Using it requires special care. The coder must invoke the destroy()
method when the Python callback is no longer needed. It means coders must track the callback's lifecycle. But this is not always possible:
Luckily the Promise
use case is automatically handled by Pyodide, but we're still left with the other cases:
from pyscript import ffi, window\n# The create_proxy is needed when a Python\n# function isn't attached to an object reference\n# (but is, rather, an argument passed into\n# the JavaScript context).\n# This is needed so a proxy is created for\n# future use, even if `print` won't ever need\n# to be freed from the Python runtime.\nwindow.setTimeout(\nffi.create_proxy(print),\n100,\n\"print\"\n)\n# This is needed because the lambda is\n# immediately garbage collected.\nwindow.setTimeout(\nffi.create_proxy(\nlambda x: print(x)\n),\n100,\n\"lambda\"\n)\ndef print_type(event):\nprint(event.type)\n# This is needed even if `print_type`\n# is not a scoped / local function.\nwindow.addEventListener(\n\"some:event\",\nffi.create_proxy(print_type),\n# despite this intent, the proxy\n# will be trapped forever if not destroyed\nffi.to_js({\"once\": True})\n)\n# This does NOT need create_function as it is\n# attached to an object reference, hence observed to free.\nwindow.Object().no_create_function = lambda: print(\"ok\")\n
To simplify this complicated situation PyScript has an experimental_create_proxy = \"auto\"
flag. When set, PyScript intercepts JavaScript callback invocations, such as those in the example code above, and automatically proxies and destroys any references that are garbage collected in the JavaScript environment.
When this flag is set to auto
in your configuration, you should never need to use create_proxy
with Pyodide.
Note
When it comes code running on a web worker, due to the way browser work, no Proxy can survive a round trip to the main thread and back.
In this scenario PyScript works differently and references callbacks via a unique id, rather than by their identity on the worker. When running on a web worker, PyScript automatically frees proxy object references, so you never need to use create_proxy
when running code on a web worker.
The proxy situation is definitely simpler in MicroPython. It just creates proxies automatically (so there is no need for a manual create_proxy
step).
This is because MicroPython doesn't (yet) have a destroy()
method for proxies, rendering the use case of create_proxy
redundant.
Accordingly, the use of create_proxy
in MicroPython is only needed for code portability purposes between Pyodide and MicroPython. When using create_proxy
in MicroPython, it's just a pass-through function and doesn't actually do anything.
All the examples that require create_proxy
in Pyodide, don't need it in MicroPython:
from pyscript import window\n# This just works.\nwindow.setTimeout(print, 100, \"print\")\n# This also just works.\nwindow.setTimeout(lambda x: print(x), 100, \"lambda\")\ndef print_type(event):\nprint(event.type)\n# This just works too.\nwindow.addEventListener(\n\"some:event\",\nprint_type,\nffi.to_js({\"once\": True})\n)\n# And so does this.\nwindow.Object().no_create_function = lambda: print(\"ok\")\n
"},{"location":"faq/#to_js","title":"to_js","text":"Use of the pyodide.ffi.to_js
function is described in the ffi page. But it's also useful to cover the when and why to_js
is needed, if at all.
Despite their apparent similarity, Python dictionaries and JavaScript object literals are very different primitives:
A Python dictionary.ref = {\"some\": \"thing\"}\n# Keys don't need quoting, but only when initialising a dict...\nref = dict(some=\"thing\")\n
A JavaScript object literal.const ref = {\"some\": \"thing\"};\n// Keys don't need quoting, so this is as equally valid...\nconst ref = {some: \"thing\"};\n
In both worlds, accessing ref[\"some\"]
would produce the same result: the string \"thing\"
.
However, in JavaScript ref.some
(i.e. a dotted reference to the key) would also work to return the string \"thing\"
(this is not the case in Python), while in Python ref.get(\"some\")
achieves the same result (and this is not the case in JavaScript).
Perhaps because of this, Pyodide chose to convert Python dictionaries to JavaScript Map objects that share a .get
method with Python.
Unfortunately, in idiomatic JavaScript and for the vast majority of APIs, an object literal (rather than a Map
) is used to represent key/value pairs. Feedback from our users indicates the dissonance of using a Map
rather than the expected object literal to represent a Python dict
is the source of a huge amount of frustration. Sadly, the APIs for Map
and object literals are sufficiently different that one cannot be a drop in replacement for another.
Pyodide have provided a way to override the default Map
based behaviour, but this results some rather esoteric code:
import js\nfrom pyodide.ffi import to_js\njs.callback(\nto_js(\n{\"async\": False},\n# Transform the default Map into an object literal.\ndict_converter=js.Object.fromEntries\n)\n)\n
Info
Thanks to a recent change in Pyodide, such Map
instances are duck-typed to behave like object literals. Conversion may not be needed anymore, and to_js
may just work without the need of the dict_converter
. Please check.
MicroPython's version of to_js
takes the opposite approach (for many of the reasons stated above) and converts Python dictionaries to object literals instead of Map
objects.
As a result, the PyScript pyscript.ffi.to_js
ALWAYS returns a JavaScript object literal by default when converting a Python dictionary no matter if you're using Pyodide or MicroPython as your interpreter. Furthermore, when using MicroPython, because things are closer to idiomatic JavaScript behaviour, you may not even need to use to_js
unless you want to ensure cross-interpreter compatibility.
Warning
When using pyscript.to_js
, the result is detached from the original Python dictionary.
Any change to the JavaScript object will not be reflected in the original Python object. For the vast majority of use cases, this is a desirable trade-off. But it's important to note this detachment.
If you're simply passing data around, pyscript.ffi.to_js
will fulfil your requirements in a simple and idiomatic manner.
Version 2.0, January 2004 <http://www.apache.org/licenses/>
"},{"location":"license/#terms-and-conditions-for-use-reproduction-and-distribution","title":"Terms and Conditions for use, reproduction, and distribution","text":""},{"location":"license/#1-definitions","title":"1. Definitions","text":"\u201cLicense\u201d shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document.
\u201cLicensor\u201d shall mean the copyright owner or entity authorized by the copyright owner that is granting the License.
\u201cLegal Entity\u201d shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, \u201ccontrol\u201d means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity.
\u201cYou\u201d (or \u201cYour\u201d) shall mean an individual or Legal Entity exercising permissions granted by this License.
\u201cSource\u201d form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files.
\u201cObject\u201d form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types.
\u201cWork\u201d shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below).
\u201cDerivative Works\u201d shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof.
\u201cContribution\u201d shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, \u201csubmitted\u201d means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as \u201cNot a Contribution.\u201d
\u201cContributor\u201d shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work.
"},{"location":"license/#2-grant-of-copyright-license","title":"2. Grant of Copyright License","text":"Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form.
"},{"location":"license/#3-grant-of-patent-license","title":"3. Grant of Patent License","text":"Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed.
"},{"location":"license/#4-redistribution","title":"4. Redistribution","text":"You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions:
You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License.
"},{"location":"license/#5-submission-of-contributions","title":"5. Submission of Contributions","text":"Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions.
"},{"location":"license/#6-trademarks","title":"6. Trademarks","text":"This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file.
"},{"location":"license/#7-disclaimer-of-warranty","title":"7. Disclaimer of Warranty","text":"Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an \u201cAS IS\u201d BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License.
"},{"location":"license/#8-limitation-of-liability","title":"8. Limitation of Liability","text":"In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages.
"},{"location":"license/#9-accepting-warranty-or-additional-liability","title":"9. Accepting Warranty or Additional Liability","text":"While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
"},{"location":"license/#appendix-how-to-apply-the-apache-license-to-your-work","title":"APPENDIX: How to apply the Apache License to your work","text":"To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets []
replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same \u201cprinted page\u201d as the copyright notice for easier identification within third-party archives.
Copyright [yyyy] [name of copyright owner]\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n
"},{"location":"user-guide/","title":"The PyScript User Guide","text":"Info
This guide provides technical guidance and exploration of the PyScript platform.
While we endeavour to write clearly, some of the content in this user guide will not be suitable for beginners. We assume you already have Python or web development experience. If you're a beginner start with our beginner's guide.
We welcome constructive feedback.
Our docs have three aims:
Read this user guide in full: it is a short but comprehensive overview of the PyScript platform.
Get involved! Join in the PyScript conversation on our discord server. There you'll find core developers, community contributors and a flourishing forum for those creating projects with PyScript. Should you wish to engage with the development of PyScript, you are welcome to contribute via the project's GitHub organisation.
Finally, the example projects referenced in our docs are all freely available and copiously commented on pyscript.com.
Note
Many of these examples come from contributors in our wonderful community. We love to recognise, share and celebrate the incredible work of folks in the PyScript community. If you believe you have a project that would make a good demonstration, please don't hesitate to get in touch.
"},{"location":"user-guide/architecture/","title":"Architecture, Lifecycle & Interpreters","text":""},{"location":"user-guide/architecture/#core-concepts","title":"Core concepts","text":"PyScript's architecture has three core concepts:
PolyScript is the core of PyScript.
Danger
Unless you are an advanced user, you only need to know that PolyScript exists, and it can be safely ignored.
PolyScript's purpose is to bootstrap the platform and provide all the necessary core capabilities. Setting aside PyScript for a moment, to use just PolyScript requires a <script>
reference to it, along with a further <script>
tag defining how to run your code.
<!doctype html>\n<html>\n<head>\n<!-- this is a way to automatically bootstrap polyscript -->\n<script type=\"module\" src=\"https://cdn.jsdelivr.net/npm/polyscript\"></script>\n</head>\n<body>\n<!--\n Run some Python code with the MicroPython interpreter, but without\n the extra benefits provided by PyScript.\n -->\n<script type=\"micropython\">\nfrom js import document\ndocument.body.textContent = 'polyscript'\n</script>\n</body>\n</html>\n
Warning
PolyScript is not PyScript.
PyScript enhances the available Python interpreters with convenient features, helper functions and easy-to-use yet powerful capabilities.
These enhancements are missing from PolyScript.
PolyScript's capabilities, upon which PyScript is built, can be summarised as:
<script>
tags.XWorker
class and its related reference, xworker
.PolyScript may become important if you encounter problems with PyScript. You should investigate PolyScript if any of the following is true about your problem:
py-*
or mpy-*
) are not triggered.We encourage you to engage and ask questions about PolyScript on our discord server. But in summary, as a user of PyScript you should probably never encounter PolyScript. However, please be aware that specific features of bug fixes my happen in the PolyScript layer in order to then land in PyScript.
"},{"location":"user-guide/architecture/#coincident","title":"Coincident","text":"Danger
Unless you are an advanced user, you only need to know that coincident exists, and it can be safely ignored. As with PolyScript, we include these details only for those interested in the more fundamental aspects of PyScript.
PolyScript uses the coincident library to seamlessly interact with web workers and coordinate interactions between the browser's main thread and such workers.
Any SharedArrayBuffer
issues are the responsibility of coincident and, to some extent, anything related to memory leaks.
In a nutshell, this project is likely responsible for the following modes of failure:
We hope all these scenarios are unlikely to happen within a PyScript project. They are all battle tested and covered with general purpose cross-environment testing before landing in PyScript. But, if you feel something is odd, leaking, or badly broken, please feel free to file an issue in the coincident project. As usual, there is never a silly question, so long as you provide a minimal reproducible example in your bug reports or query.
"},{"location":"user-guide/architecture/#the-stack","title":"The stack","text":"The stack describes how the different building blocks inside a PyScript application relate to each other:
Failure
PyScript is simply Python running in the browser. Please remember:
If the architecture explains how components relate to each other, the lifecycle explains how things unfold. It's important to understand both: it will help you think about your own code and how it sits within PyScript.
Here's how PyScript unfolds through time:
<script>
tag that references PyScript. PyScript is loaded and evaluated as a JavaScript module, meaning it doesn't hold up the loading of the page and is only evaluated when the HTML is fully parsed.<py-config>
or <mpy-config>
tags or the config
attribute of a <script>
, <py-script>
or <mpy-script>
tag).pyscript
module).py:ready
or mpy:ready
events are dispatched, depending which interpreter you've specified (Pyodide or MicroPython respectively).py:done
event is dispatched after every single script referenced from the page has finished.In addition, various \"hooks\" are called at different moments in the lifecycle of PyScript. These can be used by plugin authors to modify or enhance the behaviour of PyScript. The hooks, and how to use them, are explored further in the section on plugins.
Warning
A web page's workers have completely separate environments to the main thread.
It means configuration in the main thread can be different to that for an interpreter running on a worker. In fact, you can use different interpreters and configuration in each context (for instance, MicroPython on the main thread, and Pyodide on a worker).
Think of workers as completely separate sub-processes inside your browser tab.
"},{"location":"user-guide/architecture/#interpreters","title":"Interpreters","text":"Python is an interpreted language, and thus needs an interpreter to work.
PyScript currently supports two versions of the Python interpreter that have been compiled to WASM: Pyodide and MicroPython. You should select which one to use depending on your use case and acceptable trade-offs.
Info
In future, and subject to progress, we hope to make available a third Pythonic option: SPy, a staticially typed version of Python compiled directly to WASM.
Both interpreters make use of emscripten, a compiler toolchain (using LLVM), for emitting WASM assets for the browser. Emscripten also provides APIs so operating-system level features such as a sandboxed file system (not the user's local machine's filesystem), IO (stdin
, stdout
, stderr
etc,) and networking are available within the context of a browser.
Both Pyodide and MicroPython implement the same robust Python \u27fa JavaScript foreign function interface (FFI). This bridges the gap between the browser and Python worlds.
"},{"location":"user-guide/architecture/#pyodide","title":"Pyodide","text":"Pyodide is a version of the standard CPython interpreter, patched to compile to WASM and work in the browser.
It includes many useful features:
Warning
You may encounter an error message from micropip
that explains it can't find a \"pure Python wheel\" for a package. Pyodide's documentation explains what to do in this situation.
Briefly, some packages with C extensions have versions compiled for WASM and these can be installed with micropip
. Packages containing C extensions that are not compiled for WASM cause the \"pure Python wheel\" error.
There are plans afoot to make WASM a target in PyPI so packages with C extensions are automatically compiled to WASM.
"},{"location":"user-guide/architecture/#micropython","title":"MicroPython","text":"MicroPython is a lean and efficient implementation of the Python 3 programming language that includes a small subset of the Python standard library and is optimised to run on microcontrollers and in constrained environments (like the browser).
Everything needed to view a web page in a browser needs to be delivered over the network. The smaller the asset to be delivered can be, the better. MicroPython, when compressed for delivery to the browser, is only around 170k in size - smaller than many images found on the web.
This makes MicroPython particularly suited to browsers running in a more constrained environment such as on a mobile or tablet based device. Browsing with these devices often uses (slower) mobile internet connections. Furthermore, because MicroPython is lean and efficient it still performs exceptionally well on these relatively underpowered devices.
Thanks to collaboration between the MicroPython, Pyodide and PyScript projects, there is a foreign function interface for MicroPython. The MicroPython FFI deliberately copies the API of the FFI originally written for Pyodide - meaning it is relatively easy to migrate between the two supported interpreters via the pyscript.ffi
namespace.
The browser tab in which your PyScript based web page is displayed is a very secure sandboxed computing environment for running your Python code.
This is also the case for web workers running Python. Despite being associated with a single web page, workers are completely separate from each other (except for some very limited and clearly defined means of interacting, which PyScript looks after for you).
We need to tell PyScript how we want such Python environments to be configured. This works in the same way for both the main thread and for web workers. Such configuration ensures we get the expected resources ready before our Python code is evaluated (resources such as arbitrary data files and third party Python packages).
"},{"location":"user-guide/configuration/#toml-or-json","title":"TOML or JSON","text":"Configuration can be expressed in two formats:
Since PyScript is the marriage of Python and the web, and we respect the traditions of both technical cultures, we support both formats.
However, because JSON is built into all browsers by default and TOML requires an additional download of a specialist parser before PyScript can work, the use of JSON is more efficient from a performance point of view.
The following two configurations are equivalent, and simply tell PyScript to ensure the packages arrr and numberwang are installed from PyPI (the Python Packaging Index):
Configuration via TOML.packages = [\"arrr\", \"numberwang\" ]\n
Configuration via JSON.{\n\"packages\": [\"arrr\", \"numberwang\"]\n}\n
"},{"location":"user-guide/configuration/#file-or-inline","title":"File or inline","text":"The recommended way to write configuration is via a separate file and then reference it from the tag used to specify the Python code:
Reference a configuration file<script type=\"py\" src=\"main.py\" config=\"pyscript.toml\"></script>\n
If you use JSON, you can make it the value of the config
attribute:
<script type=\"mpy\" src=\"main.py\" config='{\"packages\":[\"arrr\", \"numberwang\"]}'></script>\n
For historical and convenience reasons we still support the inline specification of configuration information via a single <py-config>
or <mpy-config>
tag in your HTML document:
<py-config>\n{\n \"packages\": [\"arrr\", \"numberwang\" ]\n}\n</py-config>\n
Warning
Should you use <py-config>
or <mpy-config>
, there must be only one of these tags on the page per interpreter.
There are five core options (interpreter
, files
, packages
, js_modules
and sync_main_only
) and an experimental flag (experimental_create_proxy
) that can be used in the configuration of PyScript. The user is also free to define arbitrary additional configuration options that plugins or an app may require for their own reasons.
The interpreter
option pins the Python interpreter to the version of the specified value. This is useful for testing (does my code work on a specific version of Pyodide?), or to ensure the precise combination of PyScript version and interpreter version are pinned to known values.
The value of the interpreter
option should be a valid version number for the Python interpreter you are configuring, or a fully qualified URL to a custom version of the interpreter.
The following two examples are equivalent:
Specify the interpreter version in TOML.interpreter = \"0.23.4\"\n
Specify the interpreter version in JSON.{\n\"interpreter\": \"0.23.4\"\n}\n
The following JSON fragment uses a fully qualified URL to point to the same version of Pyodide as specified in the previous examples:
Specify the interpreter via a fully qualified URL.{\n\"interpreter\": \"https://cdn.jsdelivr.net/pyodide/v0.23.4/full/pyodide.mjs\"\n}\n
"},{"location":"user-guide/configuration/#files","title":"Files","text":"The files
option fetches arbitrary content from URLs onto the filesystem available to Python, and emulated by the browser. Just map a valid URL to a destination filesystem path.
The following JSON and TOML are equivalent:
Fetch files onto the filesystem with JSON.{\n\"files\": {\n\"https://example.com/data.csv\": \"./data.csv\",\n\"/code.py\": \"./subdir/code.py\"\n}\n}\n
Fetch files onto the filesystem with TOML.[files]\n\"https://example.com/data.csv\" = \"./data.csv\"\n\"/code.py\" = \"./subdir/code.py\"\n
If you make the target an empty string, the final \"filename\" part of the source URL becomes the destination filename, in the root of the filesystem, to which the content is copied. As a result, the data.csv
entry from the previous examples could be equivalently re-written as:
{\n\"files\": {\n\"https://example.com/data.csv\": \"\",\n... etc ...\n}\n}\n
TOML implied filename in the root directory.[files]\n\"https://example.com/data.csv\" = \"\"\n... etc ...\n
If the source part of the configuration is either a .zip
or .tar.gz
file and its destination is a folder path followed by a star (e.g. /*
or ./dest/*
), then PyScript will extract the referenced archive automatically into the target directory in the browser's built in file system.
Warning
PyScript expects all file destinations to be unique.
If there is a duplication PyScript will raise an exception to help you find the problem.
Tip
For most people, most of the time, the simple URL to filename mapping, described above, will be sufficient.
Yet certain situations may require more flexibility. In which case, read on.
Sometimes many resources are needed to be fetched from a single location and copied into the same directory on the file system. To aid readability and reduce repetition, the files
option comes with a mini templating language that allows reusable placeholders to be defined between curly brackets ({
and }
). When these placeholders are encountered in the files
configuration, their name is replaced with their associated value.
Attention
Valid placeholder names are always enclosed between curly brackets ({
and }
), like this: {FROM}
, {TO}
and {DATA SOURCE}
(capitalized names help identify placeholders when reading code ~ although this isn't strictly necessary).
Any number of placeholders can be defined and used anywhere within URLs and paths that map source to destination.
The following JSON and TOML are equivalent:
Using the template language in JSON.{\n\"files\": {\n\"{DOMAIN}\": \"https://my-server.com\",\n\"{PATH}\": \"a/path\",\n\"{VERSION}\": \"1.2.3\",\n\"{FROM}\": \"{DOMAIN}/{PATH}/{VERSION}\",\n\"{TO}\": \"./my_module\",\n\"{FROM}/__init__.py\": \"{TO}/__init__.py\",\n\"{FROM}/foo.py\": \"{TO}/foo.py\",\n\"{FROM}/bar.py\": \"{TO}/bar.py\",\n\"{FROM}/baz.py\": \"{TO}/baz.py\",\n}\n}\n
Using the template language in TOML.[files]\n\"{DOMAIN}\" = \"https://my-server.com\"\n\"{PATH}\" = \"a/path\"\n\"{VERSION}\" = \"1.2.3\"\n\"{FROM}\" = \"{DOMAIN}/{PATH}/{VERSION}\"\n\"{TO}\" = \"./my_module\"\n\"{FROM}/__init__.py\" = \"{TO}/__init__.py\"\n\"{FROM}/foo.py\" = \"{TO}/foo.py\"\n\"{FROM}/bar.py\" = \"{TO}/bar.py\"\n\"{FROM}/baz.py\" = \"{TO}/baz.py\"\n
The {DOMAIN}
, {PATH}
, and {VERSION}
placeholders are used to create a further {FROM}
placeholder. The {TO}
placeholder is also defined to point to a common sub-directory on the file system. The final four entries use {FROM}
and {TO}
to copy over four files (__init__.py
, foo.py
, bar.py
and baz.py
) from the same source to a common destination directory.
For convenience, if the destination is just a directory (it ends with /
) then PyScript automatically uses the filename part of the source URL as the filename in the destination directory.
For example, the end of the previous config file could be:
\"{TO}\" = \"./my_module/\"\n\"{FROM}/__init__.py\" = \"{TO}\"\n\"{FROM}/foo.py\" = \"{TO}\"\n\"{FROM}/bar.py\" = \"{TO}\"\n\"{FROM}/baz.py\" = \"{TO}\"\n
"},{"location":"user-guide/configuration/#packages","title":"Packages","text":"The packages
option lists Python packages to be installed onto the Python path.
Info
Pyodide uses a utility called micropip
to install packages from PyPI.
Because micropip
is a Pyodide-only feature, and MicroPython doesn't support code packaged on PyPI, the packages
option only works with packages hosted on PyPI when using Pyodide.
MicroPython's equivalent utility, mip
, uses a separate repository of available packages called micropython-lib
. When you use the packages
option with MicroPython, it is this repository (not PyPI) that is used to find available packages. Many of the packages in micropython-lib
are for microcontroller based activities and may not work with the web assembly port of MicroPython.
If you need pure Python modules for MicroPython, you have two further options:
The following two examples are equivalent:
A packages list in TOML.packages = [\"arrr\", \"numberwang\", \"snowballstemmer>=2.2.0\" ]\n
A packages list in JSON.{\n\"packages\": [\"arrr\", \"numberwang\", \"snowballstemmer>=2.2.0\" ]\n}\n
When using Pyodide, the names in the list of packages
can be any of the following valid forms:
\"snowballstemmer\"
\"snowballstemmer>=2.2.0\"
\"https://.../package.whl\"
\"emfs://.../package.whl\"
It's easy to import and use JavaScript modules in your Python code. This section of the docs examines the configuration needed to make this work. How to make use of JavaScript is dealt with elsewhere.
We need to tell PyScript about the JavaScript modules you want to use. This is the purpose of the js_modules
related configuration fields.
There are two fields:
js_modules.main
defines JavaScript modules loaded in the context of the main thread of the browser. Helpfully, it is also possible to interact with such modules from the context of workers. Sometimes such modules also need CSS files to work, and these can also be specified.js_modules.worker
defines JavaScript modules loaded into the context of the web worker. Such modules must not expect document
or window
references (if this is the case, you must load them via js_modules.main
and use them from the worker). However, if the JavaScript module could work without such references, then performance is better if defined on a worker. Because CSS is meaningless in the context of a worker, it is not possible to specify such files in a worker context.Once specified, your JavaScript modules will be available under the pyscript.js_modules.*
namespace.
To specify such modules, simply provide a list of source/module name pairs.
For example, to use the excellent Leaflet JavaScript module for creating interactive maps you'd add the following lines:
JavaScript main thread modules defined in TOML.[js_modules.main]\n\"https://cdn.jsdelivr.net/npm/leaflet@1.9.4/dist/leaflet-src.esm.js\" = \"leaflet\"\n\"https://cdn.jsdelivr.net/npm/leaflet@1.9.4/dist/leaflet.css\" = \"leaflet\" # CSS\n
JavaScript main thread modules defined in JSON.{\n\"js_modules\": {\n\"main\": {\n\"https://cdn.jsdelivr.net/npm/leaflet@1.9.4/dist/leaflet-src.esm.js\": \"leaflet\",\n\"https://cdn.jsdelivr.net/npm/leaflet@1.9.4/dist/leaflet.css\": \"leaflet\"\n}\n}\n}\n
Info
Notice how the second line references the required CSS needed for the JavaScript module to work correctly.
The CSS file MUST target the very same name as the JavaScript module to which it is related.
Warning
Since the Leaflet module expects to manipulate the DOM and have access to document
and window
references, it must only be added via the js_modules.main
setting (as shown) and cannot be added in a worker context.
At this point Python code running on either the main thread or in a worker will have access to the JavaScript module like this:
Making use of a JavaScript module from within Python.from pyscript.js_modules import leaflet as L\nmap = L.map(\"map\")\n# etc....\n
Some JavaScript modules (such as html-escaper) don't require access to the DOM and, for efficiency reasons, can be included in the worker context:
A JavaScript worker module defined in TOML.[js_modules.worker]\n\"https://cdn.jsdelivr.net/npm/html-escaper\" = \"html_escaper\"\n
A JavaScript worker module defined in JSON.{\n\"js_modules\": {\n\"worker\": {\n\"https://cdn.jsdelivr.net/npm/html-escaper\": \"html_escaper\"\n}\n}\n}\n
However, from pyscript.js_modules import html_escaper
would then only work within the context of Python code running on a worker.
Sometimes you just want to start an expensive computation on a web worker without the need for the worker to interact with the main thread. You're simply awaiting the result of a method exposed from a worker.
This has the advantage of not requiring the use of SharedArrayBuffer
and associated CORS related header configuration.
If the sync_main_only
flag is set, then interactions between the main thread and workers are limited to one way calls from the main thread to methods exposed by the workers.
sync_main_only = true\n
Setting the sync_main_only flag in JSON.{\n\"sync_main_only\": true\n}\n
If sync_main_only
is set, the following caveats apply:
pyscript.sync
methods are exposed, and they can only be awaited from the main thread.await
main thread references one after the other, so developer experience is degraded when one needs to interact with the main thread.Knowing when to use the pyscript.ffi.create_proxy
method when using Pyodide can be confusing at the best of times and full of technical \"magic\".
This experimental flag, when set to \"auto\"
will cause PyScript to try to automatically handle such situations, and should \"just work\".
experimental_create_proxy = \"auto\"\n
Using the experimental_create_proxy flag in JSON.{\n\"experimental_create_proxy\": \"auto\"\n}\n
Warning
This feature is experimental and only needs to be used with Pyodide.
Should you encounter problems (such as problematic memory leaks) when using this flag with Pyodide, please don't hesitate to raise an issue with a reproducable example, and we'll investigate.
"},{"location":"user-guide/configuration/#custom","title":"Custom","text":"Sometimes plugins or apps need bespoke configuration options.
So long as you don't cause a name collision with the built-in option names then you are free to use any valid data structure that works with both TOML and JSON to express your configuration needs.
Access the current configuration via pyscript.config
, a Python dict
representing the configuration:
from pyscript import config\n# It's just a dict.\nprint(config.get(\"files\"))\n
Note
Changing the config
dictionary at runtime doesn't change the actual configuration.
The DOM (document object model) is a tree like data structure representing the web page displayed by the browser. PyScript interacts with the DOM to change the user interface and react to things happening in the browser.
There are currently two ways to interact with the DOM:
globalThis
or document
objects.pydom
module that acts as a Pythonic wrapper around the FFI and comes as standard with PyScript.The foreign function interface (FFI) gives Python access to all the standard web capabilities and features, such as the browser's built-in web APIs.
This is available via the pyscript.window
module which is a proxy for the main thread's globalThis
object, or pyscript.document
which is a proxy for the website's document
object in JavaScript:
from pyscript import window, document\nmy_element = document.querySelector(\"#my-id\")\nmy_element.innerText = window.location.hostname\n
The FFI creates proxy objects in Python linked to actual objects in JavaScript.
The proxy objects in your Python code look and behave like Python objects but have related JavaScript objects associated with them. It means the API defined in JavaScript remains the same in Python, so any browser based JavaScript APIs or third party JavaScript libraries that expose objects in the web page's globalThis
, will have exactly the same API in Python as in JavaScript.
The FFI automatically transforms Python and JavaScript objects into the equivalent in the other language. For example, Python's boolean True
and False
will become JavaScript's true
and false
, while a JavaScript array of strings and integers, [\"hello\", 1, 2, 3]
becomes a Python list of the equivalent values: [\"hello\", 1, 2, 3]
.
Info
Instantiating classes into objects is an interesting special case that the FFI expects you to handle.
If you wish to instantiate a JavaScript class in your Python code, you need to call the class's new
method:
from pyscript import window\nmy_obj = window.MyJavaScriptClass.new(\"some value\")\n
The underlying reason for this is simply JavaScript and Python do instantiation very differently. By explicitly calling the JavaScript class's new
method PyScript both signals and honours this difference.
More technical information about instantiating JavaScript classes can be found in the FAQ
Should you require lower level API access to FFI features, you can find such builtin functions under the pyscript.ffi
namespace in both Pyodide and MicroPython. The available functions are described in our section on the builtin API.
Advanced users may wish to explore the technical details of the FFI.
"},{"location":"user-guide/dom/#pyscriptweb","title":"pyscript.web
","text":"Warning
The pyscript.web
module is currently a work in progress.
We welcome feedback and suggestions.
The pyscript.web
module is an idiomatically Pythonic API for interacting with the DOM. It wraps the FFI in a way that is more familiar to Python developers and works natively with the Python language. Technical documentation for this module can be found in the API section.
There are three core concepts to remember:
find
API uses exactly the same queries as those used by native browser methods like qurerySelector
or querySelectorAll
.pyscript.web
namespace to create and organise new elements on the web page.find
queries and are also used for the children of an element.You have several options for accessing the content of the page, and these are all found in the pyscript.web.page
object. The html
, head
and body
attributes reference the page's top-level html, head and body. As a convenience the page
's title
attribute can be used to get and set the web page's title (usually shown in the browser's tab). The append
method is a shortcut for adding content to the page's body
. Whereas, the find
method is used to return collections of elements matching a CSS query. You may also shortcut find
via a CSS query in square brackets. Finally, all elements have a find
method that searches within their children for elements matching your CSS query.
from pyscript.web import page\n# Print all the child elements of the document's head.\nprint(page.head.children)\n# Find all the paragraphs in the DOM.\nparagraphs = page.find(\"p\")\n# Or use square brackets.\nparagraphs = page[\"p\"]\n
The object returned from a query, or used as a reference to an element's children is iterable:
from pyscript.web import page\n# Get all the paragraphs in the DOM.\nparagraphs = page[\"p\"]\n# Print the inner html of each paragraph.\nfor p in paragraphs:\nprint(p.html)\n
Alternatively, it is also indexable / sliceable:
from pyscript.web import page\n# Get an ElementCollection of all the paragraphs in the DOM\nparagraphs = page[\"p\"]\n# Only the final two paragraphs.\nfor p in paragraphs[-2:]:\nprint(p.html)\n
You have access to all the standard attributes related to HTML elements (for example, the innerHTML
or value
), along with a couple of convenient ways to interact with classes and CSS styles:
classes
- the list of classes associated with the elements.style
- a dictionary like object for interacting with CSS style rules.For example, to continue the example above, paragraphs.innerHTML
will return a list of all the values of the innerHTML
attribute on each contained element. Alternatively, set an attribute for all elements contained in the collection like this: paragraphs.style[\"background-color\"] = \"blue\"
.
It's possible to create new elements to add to the page:
from pyscript.web import page, div, select, option, button, span, br \npage.append(\ndiv(\ndiv(\"Hello!\", classes=\"a-css-class\", id=\"hello\"),\nselect(\noption(\"apple\", value=1),\noption(\"pear\", value=2),\noption(\"orange\", value=3),\n),\ndiv(\nbutton(span(\"Hello! \"), span(\"World!\"), id=\"my-button\"),\nbr(),\nbutton(\"Click me!\"),\nclasses=[\"css-class1\", \"css-class2\"],\nstyle={\"background-color\": \"red\"}\n),\ndiv(\nchildren=[\nbutton(\nchildren=[\nspan(\"Hello! \"),\nspan(\"Again!\")\n],\nid=\"another-button\"\n),\nbr(),\nbutton(\"b\"),\n],\nclasses=[\"css-class1\", \"css-class2\"]\n)\n)\n)\n
This example demonstrates a declaritive way to add elements to the body of the page. Notice how the first (unnamed) arguments to an element are its children. The named arguments (such as id
, classes
and style
) refer to attributes of the underlying HTML element. If you'd rather be explicit about the children of an element, you can always pass in a list of such elements as the named children
argument (you see this in the final div
in the example above).
Of course, you can achieve similar results in an imperative style of programming:
from pyscript.web import page, div, p \nmy_div = div()\nmy_div.style[\"background-color\"] = \"red\"\nmy_div.classes.add(\"a-css-class\")\nmy_p = p()\nmy_p.content = \"This is a paragraph.\"\nmy_div.append(my_p)\n# etc...\n
It's also important to note that the pyscript.when
decorator understands element references from pyscript.web
:
from pyscript import when\nfrom pyscript.web import page \nbtn = page[\"#my-button\"]\n@when(\"click\", btn)\ndef my_button_click_handler(event):\nprint(\"The button has been clicked!\")\n
Should you wish direct access to the proxy object representing the underlying HTML element, each Python element has a _dom_element
property for this purpose.
Once again, the technical details of these classes are described in the built-in API documentation.
"},{"location":"user-guide/dom/#working-with-javascript","title":"Working with JavaScript","text":"There are three ways in which JavaScript can get into a web page.
window
object in the web page because the code was referenced as the source of a script
tag in your HTML (the very old school way to do this).Sadly, this being the messy world of the web, methods 1 and 2 are still quite common, and so you need to know about them so you're able to discern and work around them. There's nothing WE can do about this situation, but we can suggest \"best practice\" ways to work around each situation.
Remember, as mentioned elsewhere in our documentation, the standard way to get JavaScript modules into your PyScript Python context is to link a source standard JavaScript module to a destination name:
Reference a JavaScript module in the configuration.[js_modules.main]\n\"https://cdn.jsdelivr.net/npm/leaflet@1.9.4/dist/leaflet-src.esm.js\" = \"leaflet\"\n
Then, reference the module via the destination name in your Python code, by importing it from the pyscript.js_modules
namespace:
from pyscript.js_modules import leaflet as L\nmap = L.map(\"map\")\n# etc....\n
We'll deal with each of the potential JavaScript related situations in turn:
"},{"location":"user-guide/dom/#javascript-as-a-global-reference","title":"JavaScript as a global reference","text":"In this situation, you have some JavaScript code that just globally defines \"stuff\" in the context of your web page via a script
tag. Your HTML will contain something like this:
<!doctype html>\n<!--\nThis JS utility escapes and unescapes HTML chars. It adds an \"html\" object to\nthe global context.\n-->\n<script src=\"https://cdn.jsdelivr.net/npm/html-escaper@3.0.3/index.js\"></script>\n<!--\nVanilla JS just to check the expected object is in the global context of the\nweb page.\n-->\n<script>\nconsole.log(html);\n</script>\n
When you find yourself in this situation, simply use the window
object in your Python code (found in the pyscript
namespace) to interact with the resulting JavaScript objects:
from pyscript import window, document\n# The window object is the global context of your web page.\nhtml = window.html\n# Just use the object \"as usual\"...\n# e.g. show escaped HTML in the body: <>\ndocument.body.append(html.escape(\"<>\"))\n
You can find an example of this technique here:
https://pyscript.com/@agiammarchi/floral-glade/v1
"},{"location":"user-guide/dom/#javascript-as-a-non-standard-umd-module","title":"JavaScript as a non-standard UMD module","text":"Sadly, these sorts of non-standard JavaScript modules are still quite prevalent. But the good news is there are strategies you can use to help you get them to work properly.
The non-standard UMD approach tries to check for export
and module
fields in the JavaScript module and, if it doesn\u2019t find them, falls back to treating the module in the same way as a global reference described above.
If you find you have a UMD JavaScript module, there are services online to automagically convert it to the modern and standards compliant way to d o JavaScript modules. A common (and usually reliable) service is provided by https://esm.run/your-module-name, a service that provides an out of the box way to consume the module in the correct and standard manner:
Use esm.run to automatically convert a non-standard UMD module<!doctype html>\n<script type=\"module\">\n// this utility escapes and unescape HTML chars\nimport { escape, unescape } from \"https://esm.run/html-escaper\";\n// esm.run returns a module ^^^^^^^^^^^^^^^^^^^^^^^^^^^^\nconsole.log(escape(\"<>\"));\n// log: \"<>\"\n</script>\n
If a similar test works for the module you want to use, use the esm.run CDN service within the py
or mpy
configuration file as explained at the start of this section on JavaScript (i.e. you'll use it via the pyscript.js_modules
namespace).
If this doesn't work, assume the module is not updated nor migrated to a state that can be automatically translated by services like esm.run. You could try an alternative (more modern) JavaScript module to achieve you ends or (if it really must be this module), you can wrap it in a new JavaScript module that conforms to the modern standards.
The following four files demonstrate this approach:
index.html - still grab the script so it appears as a global reference.<!doctype html>\n...\n<!-- land the utility still globally as generic script -->\n<script src=\"https://cdn.jsdelivr.net/npm/html-escaper@3.0.3/index.js\"></script>\n...\n
wrapper.js - this grabs the JavaScript functionality from the global context and wraps it (exports it) in the modern standards compliant manner.// get all utilities needed from the global.\nconst { escape, unescape } = globalThis.html;\n// export utilities like a standards compliant module would do.\nexport { escape, unescape };\n
pyscript.toml - configure your JS modules as before, but use your wrapper instead of the original module.[js_modules.main]\n# will simulate a standard JS module\n\"./wrapper.js\" = \"html_escaper\"\n
main.py - just import the module as usual and make use of it.from pyscript import document\n# import the module either via\nfrom pyscript.js_modules import html_escaper\n# or via\nfrom pyscript.js_modules.html_escaper import escape, unescape\n# show on body: <>\ndocument.body.append(html.escape(\"<>\"))\n
You can see this approach in action here:
https://pyscript.com/@agiammarchi/floral-glade/v2
"},{"location":"user-guide/dom/#a-standard-javascript-module","title":"A standard JavaScript module","text":"This is both the easiest and best way to import any standard JS module into Python.
You don't need to reference the script in your HTML, just define how the source JavaScript module maps into the pyscript.js_modules
namespace in your configuration file, as explained above.
That's it!
Here is an example project that uses this approach:
https://pyscript.com/@agiammarchi/floral-glade/v3
"},{"location":"user-guide/dom/#my-own-javascript-code","title":"My own JavaScript code","text":"If you have your own JavaScript work, just remember to write it as a standard JavaScript module. Put simply, ensure you export
the things you need to. For instance, in the following fragment of JavaScript, the two functions are exported from the module:
/*\nSome simple JavaScript functions for example purposes.\n*/\nexport function hello(name) {\nreturn \"Hello \" + name;\n}\nexport function fibonacci(n) {\nif (n == 1) return 0;\nif (n == 2) return 1;\nreturn fibonacci(n - 1) + fibonacci(n - 2);\n}\n
Next, just reference this module in the usual way in your TOML or JSON configuration file:
pyscript.toml - references the code.js module so it will appear as the code module in the pyscript.js_modules namespace.[js_modules.main]\n\"code.js\" = \"code\"\n
In your HTML, reference your Python script with this configuration file:
Reference the expected configuration file.<script type=\"py\" src=\"./main.py\" config=\"./pyscript.toml\" terminal></script>\n
Finally, just use your JavaScript module\u2019s exported functions inside PyScript:
Just call your bespoke JavaScript code from Python.from pyscript.js_modules import code\n# Just use the JS code from Python \"as usual\".\ngreeting = code.hello(\"Chris\")\nprint(greeting)\nresult = code.fibonacci(12)\nprint(result)\n
You can see this in action in the following example project:
https://pyscript.com/@ntoll/howto-javascript/latest
"},{"location":"user-guide/editor/","title":"Python editor","text":"The PyEditor is a core plugin.
Warning
Work on the Python editor is in its early stages. We have made it available in this version of PyScript to give the community an opportunity to play, experiment and provide feedback.
Future versions of PyScript will include a more refined, robust and perhaps differently behaving version of the Python editor.
If you specify the type of a <script>
tag as either py-editor
(for Pyodide) or mpy-editor
(for MicroPython), the plugin creates a visual code editor, with code highlighting and a \"run\" button to execute the editable code contained therein in a non-blocking worker.
Info
Once clicked, the \"run\" button will show a spinner until the code is executed. This may not be visible if the code evaluation completed quickly.
The interpreter is not loaded onto the page until the run button is clicked. By default each editor has its own independent instance of the specified interpreter:
Two editors, one with Pyodide, the other with MicroPython.<script type=\"py-editor\">\nimport sys\nprint(sys.version)\n</script>\n<script type=\"mpy-editor\">\nimport sys\nprint(sys.version)\na = 42\nprint(a)\n</script>\n
However, different editors can share the same interpreter if they share the same env
attribute value.
<script type=\"mpy-editor\" env=\"shared\">\nif not 'a' in globals():\na = 1\nelse:\na += 1\nprint(a)\n</script>\n<script type=\"mpy-editor\" env=\"shared\">\n# doubled a\nprint(a * 2)\n</script>\n
The outcome of these code fragments should look something like this:
Info
Notice that the interpreter type, and optional environment name is shown at the top right above the Python editor.
Hovering over the Python editor reveals the \"run\" button.
"},{"location":"user-guide/editor/#setup","title":"Setup","text":"Sometimes you need to create a pre-baked Pythonic context for a shared environment used by an editor. This need is especially helpful in educational situations where boilerplate code can be run, with just the important salient code available in the editor.
To achieve this end use the setup
attribute within a script
tag. The content of this editor will not be shown, but will bootstrap the referenced environment automatically before any following editor within the same environment is evaluated.
<script type=\"mpy-editor\" env=\"test_env\" setup>\n# This code will not be visible, but will run before the next editor's code is\n# evaluated.\na = 1\n</script>\n<script type=\"mpy-editor\" env=\"test_env\">\n# Without the \"setup\" attribute, this editor is visible. Because it is using\n# the same env as the previous \"setup\" editor, the previous editor's code is\n# always evaluated first.\nprint(a)\n</script>\n
Finally, the target
attribute allows you to specify a node into which the editor will be rendered:
<script type=\"mpy-editor\" target=\"editor\">\nimport sys\nprint(sys.version)\n</script>\n<div id=\"editor\"></div> <!-- will eventually contain the Python editor -->\n
"},{"location":"user-guide/editor/#editor-vs-terminal","title":"Editor VS Terminal","text":"The editor and terminal are commonly used to embed interactive Python code into a website. However, there are differences between the two plugins, of which you should be aware.
The main difference is that a py-editor
or mpy-editor
is an isolated environment (from the rest of PyScript that may be running on the page) and its code always runs in a web worker. We do this to prevent accidental blocking of the main thread that would freeze your browser's user interface.
Because an editor is isolated from regular py or mpy scripts, one should not expect the same behavior regular PyScript elements follow, most notably:
Ctrl-Enter
or Cmd-Enter
, and Shift-Enter
to shortcut the execution of all the code. These shortcuts make no sense in the terminal as each line is evaluated separately.input
) with the editor, whereas these will work if running the terminal via a worker.script.terminal
or __terminal__
in the terminal.Sometimes you need to programatically read, write or execute code in an editor. Once PyScript has started, every py-editor/mpy-editor script tag gets a code
accessor attached to it.
from pyscript import document\n# Grab the editor script reference.\neditor = document.querySelector('#editor')\n# Output the live content of the editor.\nprint(editor.code)\n# Update the live content of the editor.\neditor.code = \"\"\"\na = 1\nb = 2\nprint(a + b)\n\"\"\"\n# Evaluate the live code in the editor.\n# This could be any arbitrary code to evaluate in the editor's Python context.\neditor.process(editor.code)\n
"},{"location":"user-guide/editor/#configuration","title":"Configuration","text":"Unlike <script type=\"py\">
or <py-script>
(and the mpy
equivalents), a PyEditor is not influenced by the presence of <py-config>
elements in the page: it requires an explicit config=\"...\"
attribute.
If a setup
editor is present, that's the only PyEditor that needs a config. Any subsequent related editor will reuse the config parsed and bootstrapped for the setup
editor.
Depending on your operating system, a combination of either Ctrl-Enter
, Cmd-Enter
or Shift-Enter
will execute the code in the editor (no need to move the mouse to click the run button).
Sometimes you just need to override the way the editor runs code.
The editor's handleEvent
can be overridden to achieve this:
<script type=\"mpy-editor\" id=\"foreign\">\nprint(6 * 7)\n</script>\n<script type=\"mpy\">\nfrom pyscript import document\ndef handle_event(event):\n# will log `print(6 * 7)`\nprint(event.code)\n# prevent default execution\nreturn False\n# Grab reference to the editor\nforeign = document.getElementById(\"foreign\")\n# Override handleEvent with your own customisation.\nforeign.handleEvent = handle_event\n</script>\n
This live example shows how the editor can be used to execute code via a USB serial connection to a connected MicroPython microcontroller.
"},{"location":"user-guide/editor/#tab-behavior","title":"Tab behavior","text":"We currently trap the tab
key in a way that reflects what a regular code editor would do: the code is simply indented, rather than focus moving to another element.
We are fully aware of the implications this might have around accessibility so we followed this detailed advice from Codemirror's documentation We have an escape hatch to move focus outside the editor. Press esc
before tab
to move focus to the next focusable element. Otherwise tab
indents code.
The PyEditor is currently under active development and refinement, so features may change (depending on user feedback). For instance, there is currently no way to stop or kill a web worker that has got into difficulty from the editor (hint: refreshing the page will reset things).
"},{"location":"user-guide/features/","title":"Features","text":"All the webPyscript gives you full access to the DOM and all the web APIs implemented by your browser.
Thanks to the foreign function interface (FFI), Python just works with all the browser has to offer, including any third party JavaScript libraries that may be included in the page.
The FFI is bi-directional ~ it also enables JavaScript to access the power of Python.
All of PythonPyScript brings you two Python interpreters:
Because it is just regular CPython, Pyodide puts Python's deep and diverse ecosystem of libraries, frameworks and modules at your disposal. No matter the area of computing endeavour, there's probably a Python library to help. Got a favourite library in Python? Now you can use it in the browser and share your work with just a URL.
MicroPython, because of its small size (170k) and speed, is especially suited to running on more constrained browsers, such as those on mobile or tablet devices. It includes a powerful sub-set of the Python standard library and efficiently exposes the expressiveness of Python to the browser.
Both Python interpreters supported by PyScript implement the same FFI to bridge the gap between the worlds of Python and the browser.
AI and Data science built in Python is famous for its extraordinary usefulness in artificial intelligence and data science. The Pyodide interpreter comes with many of the libraries you need for this sort of work already baked in. Mobile friendly MicroPythonThanks to MicroPython in PyScript, there is a compelling story for Python on mobile.
MicroPython is small and fast enough that your app will start quickly on first load, and almost instantly (due to the cache) on subsequent runs.
Parallel execution Thanks to a browser technology called web workers expensive and blocking computation can run somewhere other than the main application thread controlling the user interface. When such work is done on the main thread, the browser appears frozen; web workers ensure expensive blocking computation happens elsewhere. Think of workers as independent subprocesses in your web page. Rich and powerful pluginsPyScript has a small, efficient yet powerful core called PolyScript. Most of the functionality of PyScript is actually implemented through PolyScript's plugin system.
This approach ensures a clear separation of concerns: PolyScript can focus on being small, efficient and powerful, whereas the PyScript related plugins allow us to Pythonically build upon the solid foundations of PolyScript.
Because there is a plugin system, folks independent of the PyScript core team have a way to create and contribute to a rich ecosystem of plugins whose functionality reflects the unique and diverse needs of PyScript's users.
"},{"location":"user-guide/ffi/","title":"PyScript FFI","text":"The foreign function interface (FFI) gives Python access to JavaScript, and JavaScript access to Python. As a result PyScript is able to access all the standard APIs and capabilities provided by the browser.
We provide a unified pyscript.ffi
because Pyodide's FFI is only partially implemented in MicroPython and there are some fundamental differences. The pyscript.ffi
namespace smooths out such differences into a uniform and consistent API.
Our pyscript.ffi
offers the following utilities:
ffi.to_js(reference)
converts a Python object into its JavaScript counterpart.ffi.create_proxy(def_or_lambda)
proxies a generic Python function into a JavaScript one, without destroying its reference right away.Should you require access to Pyodide or MicroPython's specific version of the FFI you'll find them under the pyodide.ffi
and micropython.ffi
namespaces. Please refer to the documentation for those projects for further information.
In the Pyodide project, this utility converts Python dictionaries into JavaScript Map
objects. Such Map
objects reflect the obj.get(field)
semantics native to Python's way of retrieving a value from a dictionary.
Unfortunately, this default conversion breaks the vast majority of native and third party JavaScript APIs. This is because the convention in idiomatic JavaScript is to use an object for such key/value data structures (not a Map
instance).
A common complaint has been the repeated need to call to_js
with the long winded argument dict_converter=js.Object.fromEntries
. It turns out, most people most of the time simply want to map a Python dict
to a JavaScript object
(not a Map
).
Furthermore, in MicroPython the default Python dict
conversion is to the idiomatic and sensible JavaScript object
, making the need to specify a dictionary converter pointless.
Therefore, if there is no reason to hold a Python reference in a JavaScript context (which is 99% of the time, for common usage of PyScript) then use the pyscript.ffi.to_js
function, on both Pyodide and MicroPython, to always convert a Python dict
to a JavaScript object
.
<!-- works on Pyodide (type py) only -->\n<script type=\"py\">\nfrom pyodide.ffi import to_js\n# default into JS new Map([[\"a\", 1], [\"b\", 2]])\nto_js({\"a\": 1, \"b\": 2})\n</script>\n<!-- works on both Pyodide and MicroPython -->\n<script type=\"py\">\nfrom pyscript.ffi import to_js\n# always default into JS {\"a\": 1, \"b\": 2}\nto_js({\"a\": 1, \"b\": 2})\n</script>\n
Note
It is still possible to specify a different dict_converter
or use Pyodide specific features while converting Python references by simply overriding the explicit field for dict_converter
.
However, we cannot guarantee all fields and features provided by Pyodide will work in the same way on MicroPython.
"},{"location":"user-guide/ffi/#create_proxy","title":"create_proxy","text":"In the Pyodide project, this function ensures that a Python callable associated with an event listener, won't be garbage collected immediately after the function is assigned to the event. Therefore, in Pyodide, if you do not wrap your Python function, it is immediately garbage collected after being associated with an event listener.
This is so common a gotcha (see the FAQ for more on this) that the Pyodide project have already created many work-arounds to address this situation. For example, the create_once_callable
, pyodide.ffi.wrappers.add_event_listener
and pyodide.ffi.set_timeout
are all methods whose goal is to automatically manage the lifetime of the passed in Python callback.
Add to this situation methods connected to the JavaScript Promise
object (.then
and .catch
callbacks that are implicitly handled to guarantee no leaks once executed) and things start to get confusing and overwhelming with many ways to achieve a common end result.
Ultimately, user feedback suggests folks simply want to do something like this, as they write their Python code:
Define a callback without create_proxy.import js\nfrom pyscript import window\ndef callback(msg):\n\"\"\"\n A Python callable that logs a message.\n \"\"\"\nwindow.console.log(msg)\n# Use the callback without having to explicitly create_proxy.\njs.setTimeout(callback, 1000, 'success')\n
Therefore, PyScript provides an experimental configuration flag called experimental_create_proxy = \"auto\"
. When set, you should never have to care about these technical details nor use the create_proxy
method and all the JavaScript callback APIs should just work.
Under the hood, the flag is strictly coupled with the JavaScript garbage collector that will eventually destroy all proxy objects created via the FinalizationRegistry built into the browser.
This flag also won't affect MicroPython because it rarely needs a create_proxy
at all when Python functions are passed to JavaScript event handlers. MicroPython automatically handles this situation. However, there might still be rare and niche cases in MicroPython where such a conversion might be needed.
Hence, PyScript retains the create_proxy
method, even though it does not change much in the MicroPython world, although it might be still needed with the Pyodide runtime is you don't use the experimental_create_proxy = \"auto\"
flag.
At a more fundamental level, MicroPython doesn't provide (yet) a way to explicitly destroy a proxy reference, whereas Pyodide still expects to explicitly invoke proxy.destroy()
when the function is not needed.
Warning
In MicroPython proxies might leak due to the lack of a destroy()
method.
Happily, proxies are usually created explicitly for event listeners or other utilities that won't need to be destroyed in the future. So the lack of a destroy()
method in MicroPython is not a problem in this specific, and most common, situation.
Until we have a destroy()
in MicroPython, we suggest testing the experimental_create_proxy
flag with Pyodide so both runtimes handle possible leaks automatically.
For completeness, the following examples illustrate the differences in behaviour between Pyodide and MicroPython:
A classic Pyodide gotcha VS MicroPython<!-- Throws:\nUncaught Error: This borrowed proxy was automatically destroyed\nat the end of a function call. Try using create_proxy or create_once_callable.\n-->\n<script type=\"py\">\nimport js\njs.setTimeout(lambda x: print(x), 1000, \"fail\");\n</script>\n<!-- logs \"success\" after a second -->\n<script type=\"mpy\">\nimport js\njs.setTimeout(lambda x: print(x), 1000, \"success\");\n</script>\n
To address the difference in Pyodide's behaviour, we can use the experimental flag:
experimental create_proxy<py-config>\n experimental_create_proxy = \"auto\"\n</py-config>\n<!-- logs \"success\" after a second in both Pyodide and MicroPython -->\n<script type=\"py\">\nimport js\njs.setTimeout(lambda x: print(x), 1000, \"success\");\n</script>\n
Alternatively, create_proxy
via the pyscript.ffi
in both interpreters, but only in Pyodide can we then destroy such proxy:
<!-- success in both Pyodide and MicroPython -->\n<script type=\"py\">\nfrom pyscript.ffi import create_proxy\nimport js\ndef log(x):\ntry:\nproxy.destroy()\nexcept:\npass # MicroPython\nprint(x)\nproxy = create_proxy(log)\njs.setTimeout(proxy, 1000, \"success\");\n</script>\n
"},{"location":"user-guide/first-steps/","title":"First steps","text":"It's simple:
That's it!
For the browser to use PyScript, simply add a <script>
tag, whose src
attribute references a CDN url for pyscript.core
, to your HTML document's <head>
. We encourage you to add a reference to optional PyScript related CSS:
<!doctype html>\n<html>\n<head>\n<!-- Recommended meta tags -->\n<meta charset=\"UTF-8\">\n<meta name=\"viewport\" content=\"width=device-width,initial-scale=1.0\">\n<!-- PyScript CSS -->\n<link rel=\"stylesheet\" href=\"https://pyscript.net/releases/2024.9.1/core.css\">\n<!-- This script tag bootstraps PyScript -->\n<script type=\"module\" src=\"https://pyscript.net/releases/2024.9.1/core.js\"></script>\n</head>\n<body>\n<!-- your code goes here... -->\n</body>\n</html>\n
There are two ways to tell PyScript how to find your code.
<script>
tag whose type
attribute is either py
(for Pyodide) or mpy
(for MicroPython). This is the recommended way.<py-script>
(Pyodide) and <mpy-script>
(MicroPython) tags. Historically, <py-script>
used to be the only way to reference your code.These should be inserted into the <body>
of your HTML document.
In both cases either use the src
attribute to reference a Python file containing your code, or inline your code between the opening and closing tags. We recommend you use the src
attribute method, but retain the ability to include code between tags for convenience.
Here's a <script>
tag with a src
attribute containing a URL pointing to a main.py
Python file.
<script type=\"mpy\" src=\"main.py\"></script>\n
...and here's a <py-script>
tag with inline Python code.
<py-script>\nimport sys\nfrom pyscript import display\n\ndisplay(sys.version)\n</py-script>\n
The <script>
and <py-script>
/ <mpy-script>
tags may have the following attributes:
src
- the content of the tag is ignored and the Python code in the referenced file is evaluated instead. This is the recommended way to reference your Python code.config
- your code will only be evaluated after the referenced configuration has been parsed. Since configuration can be JSON or a TOML file, config='{\"packages\":[\"numpy\"]}'
and config=\"./config.json\"
or config=\"./config.toml\"
are all valid.async
- set this flag to \"false\"
so your code won't run within a top level await (the default behaviour).Warning
This behaviour changed in version 2024.8.2.
PyScript now uses a top level await by default.
You used to have to include the async
flag to enable this. Now, instead, use async=\"false\"
to revert the behaviour back to the old default behaviour of synchronous evaluation.
We made this change because many folks were await
-ing functions and missing or not realising the need for the (old) async
attribute. Hence the flip in behaviour.
worker
- a flag to indicate your Python code is to be run on a web worker instead of the \"main thread\" that looks after the user interface.target
- the id or selector of the element where calls to display()
should write their values. terminal
- a traditional terminal is shown on the page. As with conventional Python, print
statements output here. If the worker
flag is set the terminal becomes interactive (e.g. use the input
statement to gather characters typed into the terminal by the user).service-worker
- an optional attribute that allows you to slot in a custom service worker (such as mini-coi.js
) to fix header related problems that limit the use of web workers. This rather technical requirement is fully explained in the section on web workers.Warning
The packages
setting used in the example configuration shown above is for Pyodide using PyPI.
When using MicroPython, and because MicroPython doesn't support code packaged on PyPI, you should use a valid URL to a MicroPython friendly package.
For more information please refer to the packages section of this user guide.
Question
Why do we recommend use of the <script>
tag with a src
attribute?
Within the HTML standard, the <script>
tag is used to embed executable code. Its use case completely aligns with our own, as does its default behaviour.
By referencing a separate Python source file via the src
attribute, your code is just a regular Python file your code editor will understand. Python code embedded within a <script>
tag in an HTML file won't benefit from the advantages code editors bring: syntax highlighting, code analysis, language-based contextual awareness and perhaps even an AI co-pilot.
Both the <py-script>
and <mpy-script>
tags with inline code are web components that are not built into the browser. While they are convenient, there is a performance cost to their use.
Info
The browser's tab displaying the website running PyScript is an isolated computing sandbox. Define the Python environment in which your code will run with configuration options (discussed later in this user guide).
Tip
If you want to run code on both the main thread and in a worker, be explicit and use separate tags.
<script type=\"mpy\" src=\"main.py\"></script> <!-- on the main thread -->\n<script type=\"py\" src=\"worker.py\" worker config=\"pyconfig.toml\"></script> <!-- on the worker -->\n
Notice how different interpreters can be used with different configurations.
"},{"location":"user-guide/offline/","title":"Use PyScript Offline","text":"Sometimes you want to run PyScript applications offline.
Both PyScript core and the interpreter used to run code need to be served with the application itself. The two requirements needed to create an offline version of PyScript are:
You have two choices:
./dist/
folder.In the following instructions, we assume the existence of a folder called pyscript-offline
. All the necessary files needed to use PyScript offline will eventually find their way in there.
In your computer's command line shell, create the pyscript-offline
folder like this:
mkdir -p pyscript-offline\n
Now change into the newly created directory:
cd pyscript-offline\n
"},{"location":"user-guide/offline/#pyscipt-core-from-source","title":"PyScipt core from source","text":"Build PyScript core by cloning the project repository and follow the instructions in our developer guide
Once completed, copy the dist
folder, that has been created by the build step, into your pyscript-offline
folder.
npm
","text":"Ensure you are in the pyscript-offline
folder created earlier.
Create a package.json
file. Even an empty one with just {}
as content will suffice. This is needed to make sure our folder will include the local npm_modules
folder instead of placing assets elsewhere. Our aim is to ensure everything is in the same place locally.
# only if there is no package.json, create one\necho '{}' > ./package.json\n
Assuming you have npm installed on your computer, issue the following command in the pyscript-offline
folder to install the PyScript core package.
# install @pyscript/core\nnpm i @pyscript/core\n
Now the folder should contain a node_module
folder in it, and we can copy the dist
folder found within the @pyscript/core
package wherever we like.
# create a public folder to serve locally\nmkdir -p public\n\n# move @pyscript/core dist into such folder\ncp -R ./node_modules/@pyscript/core/dist ./public/pyscript\n
That's almost it!
"},{"location":"user-guide/offline/#set-up-your-application","title":"Set up your application","text":"Simply create a ./public/index.html
file that loads the local PyScript:
<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n<meta charset=\"UTF-8\">\n<meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">\n<title>PyScript Offline</title>\n<script type=\"module\" src=\"/pyscript/core.js\"></script>\n<link rel=\"stylesheet\" href=\"/pyscript/core.css\">\n</head>\n<body>\n<script type=\"mpy\">\nfrom pyscript import document\ndocument.body.append(\"Hello from PyScript\")\n</script>\n</body>\n</html>\n
Run this project directly (after being sure that index.html
file is saved into the public
folder):
python3 -m http.server -d ./public/\n
If you would like to test worker
features, try instead:
npx mini-coi ./public/\n
"},{"location":"user-guide/offline/#download-a-local-interpreter","title":"Download a local interpreter","text":"PyScript officially supports MicroPython and Pyodide interpreters, so let's see how to get a local copy for each one of them.
"},{"location":"user-guide/offline/#local-micropython","title":"Local MicroPython","text":"Similar to @pyscript/core
, we can also install MicroPython from npm:
npm i @micropython/micropython-webassembly-pyscript\n
Our node_modules
folder should contain a @micropython
one and from there we can move relevant files into our public
folder.
Let's be sure we have a target for that:
# create a folder in our public space\nmkdir -p ./public/micropython\n\n# copy related files into such folder\ncp ./node_modules/@micropython/micropython-webassembly-pyscript/micropython.* ./public/micropython/\n
The folder should contain at least both micropython.mjs
and micropython.wasm
files. These are the files to use locally via a dedicated config.
<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n<meta charset=\"UTF-8\">\n<meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">\n<title>PyScript Offline</title>\n<script type=\"module\" src=\"/pyscript/core.js\"></script>\n<link rel=\"stylesheet\" href=\"/pyscript/core.css\">\n</head>\n<body>\n<mpy-config>\n interpreter = \"/micropython/micropython.mjs\"\n </mpy-config>\n<script type=\"mpy\">\nfrom pyscript import document\ndocument.body.append(\"Hello from PyScript\")\n</script>\n</body>\n</html>\n
"},{"location":"user-guide/offline/#local-pyodide","title":"Local Pyodide","text":"Remember, Pyodide uses micropip
to install third party packages. While the procedure for offline Pyodide is very similar to the one for MicroPython, if we want to use 3rd party packages we also need to have these available locally. We'll start simple and cover such packaging issues at the end.
# locally install the pyodide module\nnpm i pyodide\n\n# create a folder in our public space\nmkdir -p ./public/pyodide\n\n# move all necessary files into that folder\ncp ./node_modules/pyodide/pyodide* ./public/pyodide/\ncp ./node_modules/pyodide/python_stdlib.zip ./public/pyodide/\n
Please note that the pyodide-lock.json
file is needed, so please don't change that cp
operation as all pyodide*
files need to be moved.
At this point, all we need to do is to change the configuration on our HTML page to use pyodide instead:
<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n<meta charset=\"UTF-8\">\n<meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">\n<title>PyScript Offline</title>\n<script type=\"module\" src=\"/pyscript/core.js\"></script>\n<link rel=\"stylesheet\" href=\"/pyscript/core.css\">\n</head>\n<body>\n<py-config>\n interpreter = \"/pyodide/pyodide.mjs\"\n </py-config>\n<script type=\"py\">\nfrom pyscript import document\ndocument.body.append(\"Hello from PyScript\")\n</script>\n</body>\n</html>\n
"},{"location":"user-guide/offline/#wrap-up","title":"Wrap up","text":"That's basically it!
Disconnect from the internet, run the local server, and the page will still show that very same Hello from PyScript
message.
Finally, we need the ability to install Python packages from a local source when using Pyodide.
Put simply, we use the packages bundle from pyodide releases.
Warning
This bundle is more than 200MB!
It contains each package that is required by Pyodide, and Pyodide will only load packages when needed.
Once downloaded and extracted (we're using version 0.26.2
in this example), we can simply copy the files and folders inside the pyodide-0.26.2/pyodide/*
directory into our ./public/pyodide/*
folder.
Feel free to either skip or replace the content, or even directly move the pyodide
folder inside our ./public/
one.
Now use any package available in via the Pyodide bundle.
For example:
<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n<meta charset=\"UTF-8\">\n<meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">\n<title>PyScript Offline</title>\n<script type=\"module\" src=\"/pyscript/core.js\"></script>\n<link rel=\"stylesheet\" href=\"/pyscript/core.css\">\n</head>\n<body>\n<py-config>\n interpreter = \"/pyodide/pyodide.mjs\"\n packages = [\"pandas\"]\n </py-config>\n<script type=\"py\">\nimport pandas as pd\nx = pd.Series([1,2,3,4,5,6,7,8,9,10])\nfrom pyscript import document\ndocument.body.append(str([i**2 for i in x]))\n</script>\n</body>\n</html>\n
We should now be able to read [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
on the page even if we disconnect from the Internet.
That's it!
"},{"location":"user-guide/plugins/","title":"Plugins","text":"PyScript offers a plugin API so anyone can extend its functionality and share their modifications.
PyScript only supports plugins written in Javascript (although causing the evaluation of bespoke Python code can be a part of such plugins). The plugin's JavaScript code should be included on the web page via a <script type=\"module\">
tag before PyScript is included in the web page.
The PyScript plugin API defines hooks that intercept named events in the lifecycle of a PyScript application, so you can modify how the platform behaves. The example at the bottom of this page demonstrates how this is done in code.
"},{"location":"user-guide/plugins/#lifecycle-events","title":"Lifecycle Events","text":"PyScript emits events that capture the beginning or the end of specific stages in the application's life. No matter if code is running in the main thread or on a web worker, the exact same sequence of steps takes place:
script
or tag, and the associated Python interpreter is ready to work. A JavaScript callback can be used to instrument the interpreter before anything else happens.script
or other PyScript related tags is evaluated.PyScript's interpreters can run their code either synchronously or asynchronously (note, the default is asynchronously). No matter, the very same sequence is guaranteed to run in order in both cases, the only difference being the naming convention used to reference synchronous or asynchronous lifecycle hooks.
"},{"location":"user-guide/plugins/#hooks","title":"Hooks","text":"Hooks are used to tell PyScript that your code wants to subscribe to specific lifecycle events. When such events happen, your code will be called by PyScript.
The available hooks depend upon where your code is running: on the browser's (blocking) main thread or on a (non-blocking) web worker. These are defined via the hooks.main
and hooks.worker
namespaces in JavaScript.
Callbacks registered via hooks on the main thread will usually receive a wrapper of the interpreter with its unique-to-that-interpreter utilities, along with a reference to the element on the page from where the code was derived.
Please refer to the documentation for the interpreter you're using (Pyodide or MicroPython) to learn about its implementation details and the potential capabilities made available via the wrapper.
Callbacks whose purpose is simply to run raw contextual Python code, don't receive interpreter or element arguments.
This table lists all possible, yet optional, hooks a plugin can register on the main thread:
name example behavior onReadyonReady(wrap:Wrap, el:Element) {}
If defined, this hook is invoked before any other to signal that the interpreter is ready and code is going to be evaluated. This hook is in charge of eventually running Pythonic content in any way it is defined to do so. onBeforeRun onBeforeRun(wrap:Wrap, el:Element) {}
If defined, it is invoked before to signal that an element's code is going to be evaluated. onBeforeRunAsync onBeforeRunAsync(wrap:Wrap, el:Element) {}
Same as onBeforeRun
, except for scripts that require async
behaviour. codeBeforeRun codeBeforeRun: () => 'print(\"before\")'
If defined, evaluate some Python code immediately before the element's code is evaluated. codeBeforeRunAsync codeBeforeRunAsync: () => 'print(\"before\")'
Same as codeBeforeRun,
except for scripts that require async
behaviour. codeAfterRun codeAfterRun: () => 'print(\"after\")'
If defined, evaluate come Python code immediately after the element's code has finished executing. codeAfterRunAsync codeAfterRunAsync: () => 'print(\"after\")'
Same as codeAfterRun
, except for scripts that require async
behaviour. onAfterRun onAfterRun(wrap:Wrap, el:Element) {}
If defined, invoked immediately after the element's code has been executed. onAfterRunAsync onAfterRunAsync(wrap:Wrap, el:Element) {}
Same as onAfterRun
, except for scripts that require async
behaviour. onWorker onWorker(wrap = null, xworker) {}
If defined, whenever a script or tag with a worker
attribute is processed, this hook is triggered on the main thread. This allows possible xworker
features to be exposed before the code is evaluated on the web worker. The wrap
reference is usually null
unless an explicit XWorker
call has been initialized manually and there is an interpreter on the main thread (very advanced use case). Please note, this is the only hook that doesn't exist in the worker counter list of hooks."},{"location":"user-guide/plugins/#worker-hooks","title":"Worker Hooks","text":"When it comes to hooks on a web worker, callbacks cannot use any JavaScript outer scope references and must be completely self contained. This is because callbacks must be serializable in order to work on web workers since they are actually communicated as strings via a postMessage to the worker's isolated environment.
For example, this will work because all references are contained within the registered function:
import { hooks } from \"https://pyscript.net/releases/2024.9.1/core.js\";\nhooks.worker.onReady.add(() => {\n// NOT suggested, just an example!\n// This code simply defines a global `i` reference if it doesn't exist.\nif (!('i' in globalThis))\nglobalThis.i = 0;\nconsole.log(++i);\n});\n
However, due to the outer reference to the variable i
, this will fail:
import { hooks } from \"https://pyscript.net/releases/2024.9.1/core.js\";\n// NO NO NO NO NO! \u2620\ufe0f\nlet i = 0;\nhooks.worker.onReady.add(() => {\n// The `i` in the outer-scope will cause an error if\n// this code executes in the worker because only the\n// body of this function gets stringified and re-evaluated\nconsole.log(++i);\n});\n
As the worker won't have an element
related to it, since workers can be created procedurally, the second argument won't be a reference to an element
but a reference to the related xworker
object that is driving and coordinating things.
The list of possible yet optional hooks a custom plugin can use with a web worker is exactly the same as for the main thread except for the absence of onWorker
and the replacement of the second element
argument with that of an xworker
.
Here's a contrived example, written in JavaScript, that should be added to the web page via a <script type=\"module\">
tag before PyScript is included in the page.
// import the hooks from PyScript first...\nimport { hooks } from \"https://pyscript.net/releases/2024.9.1/core.js\";\n// The `hooks.main` attribute defines plugins that run on the main thread.\nhooks.main.onReady.add((wrap, element) => {\nconsole.log(\"main\", \"onReady\");\nif (location.search === '?debug') {\nconsole.debug(\"main\", \"wrap\", wrap);\nconsole.debug(\"main\", \"element\", element);\n}\n});\nhooks.main.onBeforeRun.add(() => {\nconsole.log(\"main\", \"onBeforeRun\");\n});\nhooks.main.codeBeforeRun.add('print(\"main\", \"codeBeforeRun\")');\nhooks.main.codeAfterRun.add('print(\"main\", \"codeAfterRun\")');\nhooks.main.onAfterRun.add(() => {\nconsole.log(\"main\", \"onAfterRun\");\n});\n// The `hooks.worker` attribute defines plugins that run on workers.\nhooks.worker.onReady.add((wrap, xworker) => {\nconsole.log(\"worker\", \"onReady\");\nif (location.search === '?debug') {\nconsole.debug(\"worker\", \"wrap\", wrap);\nconsole.debug(\"worker\", \"xworker\", xworker);\n}\n});\nhooks.worker.onBeforeRun.add(() => {\nconsole.log(\"worker\", \"onBeforeRun\");\n});\nhooks.worker.codeBeforeRun.add('print(\"worker\", \"codeBeforeRun\")');\nhooks.worker.codeAfterRun.add('print(\"worker\", \"codeAfterRun\")');\nhooks.worker.onAfterRun.add(() => {\nconsole.log(\"worker\", \"onAfterRun\");\n});\n
Include the plugin in the web page before including PyScript.<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n<meta charset=\"UTF-8\">\n<meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">\n<!-- JS plugins should be available before PyScript bootstraps -->\n<script type=\"module\" src=\"./log.js\"></script>\n<!-- PyScript -->\n<link rel=\"stylesheet\" href=\"https://pyscript.net/releases/2024.9.1/core.css\">\n<script type=\"module\" src=\"https://pyscript.net/releases/2024.9.1/core.js\"></script>\n</head>\n<body>\n<script type=\"mpy\">\nprint(\"ACTUAL CODE\")\n</script>\n</body>\n</html>\n
"},{"location":"user-guide/running-offline/","title":"Running PyScript Offline","text":"Although users will want to create and share PyScript apps on the internet, there are cases when user want to run PyScript applications offline, in an airgapped fashion. This means that both PyScript core and the interpreter used to run code need to be served with the application itself. In short, the 2 main explicit tasks needed to create an offline PyScript application are:
core.js
)core.js
","text":"There are at least 2 ways to use PyScript offline:
./dist/
folderIn the examples below, we'll assume we are creating a PyScript Application folder called pyscript-offline
and we'll add all the necessary files to the folder.
First of all, we are going to create a pyscript-offline
folder as reference.
mkdir -p pyscript-offline\ncd pyscript-offline\n
"},{"location":"user-guide/running-offline/#adding-core-by-cloning-the-repository","title":"Adding core by Cloning the Repository","text":"You can build all the PyScript Core files by cloning the project repository and building them yourself. To do so, build the files by following the instructions in our developer guide
Once you've run the build
command, copy the build
folder that has been created into your pyscript-offline
folder.
@pyscript/core
Locally","text":"First of all, ensure you are in the folder you would like to test PyScirpt locally. In this case, the pyscript-offline
folder we created earlier.
Once within the folder, be sure there is a package.json
file. Even an empty one with just {}
as content would work. This is needed to be sure the folder will include locally the npm_modules
folder instead of placing the package in the parent folder, if any.
# only if there is no package.json, create one\necho '{}' > ./package.json\n\n# install @pyscript/core\nnpm i @pyscript/core\n
At this point the folder should contain a node_module
in it and we can actually copy its dist
folder wherever we like.
# create a public folder to serve locally\nmkdir -p public\n\n# move @pyscript/core dist into such folder\ncp -R ./node_modules/@pyscript/core/dist ./public/pyscript\n
"},{"location":"user-guide/running-offline/#setting-up-your-application","title":"Setting up your application","text":"Once you've added PyScript code following one of the methods above, that's almost it! We are half way through our goal but we can already create a ./public/index.html
file that loads the project:
<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n<meta charset=\"UTF-8\">\n<meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">\n<title>PyScript Offline</title>\n<script type=\"module\" src=\"/pyscript/core.js\"></script>\n<link rel=\"stylesheet\" href=\"/pyscript/core.css\">\n</head>\n<body>\n<script type=\"mpy\">\nfrom pyscript import document\ndocument.body.append(\"Hello from PyScript\")\n</script>\n</body>\n</html>\n
To run this project directly, after being sure that index.html
file is saved into the public
folder, you can try:
python3 -m http.server -d ./public/\n
Alternatively, if you would like to test also worker
features, you can try instead:
npx static-handler --coi ./public/\n
"},{"location":"user-guide/running-offline/#downloading-and-setting-up-a-local-interpreter","title":"Downloading and Setting up a Local Interpreter","text":"Good news! We are almost there. Now that we've:
we need to download and setup up an interpreter. PyScript officially supports MicroPython and Pyodide interpreters, so let's see how to do that for each one of them.
"},{"location":"user-guide/running-offline/#download-micropython-locally","title":"Download MicroPython locally","text":"Similarly to what we did for @pyscript/core
, we can also install MicroPython from npm:
npm i @micropython/micropython-webassembly-pyscript\n
Our node_modules
folder now should contain a @micropython
one and from there we can move relevant files into our public
folder, but let's be sure we have a target for that:
# create a folder in our public space\nmkdir -p ./public/micropython\n\n# copy related files into such folder\ncp ./node_modules/@micropython/micropython-webassembly-pyscript/micropython.* ./public/micropython/\n
That folder should contain at least both micropython.mjs
and micropython.wasm
files and these are the files we are going to use locally via our dedicated config.
<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n<meta charset=\"UTF-8\">\n<meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">\n<title>PyScript Offline</title>\n<script type=\"module\" src=\"/pyscript/core.js\"></script>\n<link rel=\"stylesheet\" href=\"/pyscript/core.css\">\n</head>\n<body>\n<mpy-config>\n interpreter = \"/micropython/micropython.mjs\"\n </mpy-config>\n<script type=\"mpy\">\nfrom pyscript import document\ndocument.body.append(\"Hello from PyScript\")\n</script>\n</body>\n</html>\n
"},{"location":"user-guide/running-offline/#install-pyodide-locally","title":"Install Pyodide locally","text":"Currently there is a difference between MicroPython and Pyodide: the former does not have (yet) a package manager while the latest does, it's called micropip.
This is important to remember because while the procedure to have pyodide offline is very similar to the one we've just seen, if we want to use also 3rd party packages we also need to have these running locally ... but let's start simple:
# install locally the pyodide module\nnpm i pyodide\n\n# create a folder in our public space\nmkdir -p ./public/pyodide\n\n# move all necessary files into that folder\ncp ./node_modules/pyodide/pyodide* ./public/pyodide/\ncp ./node_modules/pyodide/python_stdlib.zip ./public/pyodide/\n
Please note that also pyodide-lock.json
file is needed so please don't change that cp
operation as all pyodide*
files need to be moved.
At this point, all we need to do is to change our HTML page to use pyodide instead:
<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n<meta charset=\"UTF-8\">\n<meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">\n<title>PyScript Offline</title>\n<script type=\"module\" src=\"/pyscript/core.js\"></script>\n<link rel=\"stylesheet\" href=\"/pyscript/core.css\">\n</head>\n<body>\n<py-config>\n interpreter = \"/pyodide/pyodide.mjs\"\n </py-config>\n<script type=\"py\">\nfrom pyscript import document\ndocument.body.append(\"Hello from PyScript\")\n</script>\n</body>\n</html>\n
"},{"location":"user-guide/running-offline/#wrapping-it-up","title":"Wrapping it up","text":"We are basically done! If we try to disconnect from the internet but we still run our local server, the page will still show that very same Hello from PyScript message :partying_face:
We can now drop internet, still keeping the local server running, and everything should be fine :partying_face:
"},{"location":"user-guide/running-offline/#local-pyodide-packages","title":"Local Pyodide Packages","text":"There's one last thing that users are probably going to need: the ability to install Python packages when using Pyodide.
In order to have also 3rd party packages available, we can use the bundle from pyodide releases that contains also packages.
Please note this bundle is more than 200MB: it not downloaded all at once, it contains each package that is required and it loads only related packages when needed.
Once downloaded and extracted, where in this case I am using 0.24.1
as reference bundle, we can literally copy and paste, or even move, all those files and folders inside the pyodide-0.24.1/pyodide/*
directory into our ./public/pyodide/*
folder.
As the bundle contains files already present, feel free to either skip or replace the content, or even directly move that pyodide folder inside our ./public/
one.
Once it's done, we can now use any package we like that is available in pyodide. Let's see an example:
<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n<meta charset=\"UTF-8\">\n<meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">\n<title>PyScript Offline</title>\n<script type=\"module\" src=\"/pyscript/core.js\"></script>\n<link rel=\"stylesheet\" href=\"/pyscript/core.css\">\n</head>\n<body>\n<py-config>\n interpreter = \"/pyodide/pyodide.mjs\"\n packages = [\"pandas\"]\n </py-config>\n<script type=\"py\">\nimport pandas as pd\nx = pd.Series([1,2,3,4,5,6,7,8,9,10])\nfrom pyscript import document\ndocument.body.append(str([i**2 for i in x]))\n</script>\n</body>\n</html>\n
If everything went fine, we should now be able to read [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
on the page even if we disconnect from the Internet.
And that's all folks :wave:
"},{"location":"user-guide/terminal/","title":"Terminal","text":"In conventional (non-browser based) Python, it is common to run scripts from the terminal, or to interact directly with the Python interpreter via the REPL. It's to the terminal that print
writes characters (via stdout
), and it's from the terminal that the input
reads characters (via stdin
).
It usually looks something like this:
Because of the historic importance of the use of a terminal, PyScript makes one available in the browser (based upon XTerm.js). As mentioned earlier, PyScript's built-in terminal is activated with the terminal
flag when using the <script>
, <py-script>
or <mpy-script>
tags.
Success
As of the 2024.4.1 release, MicroPython works with the terminal.
This is, perhaps, the simplest use case that allows data to be emitted to a read-only terminal:
<script type=\"py\" terminal>print(\"hello world\")</script>\n
The end result will look like this (the rectangular box indicates the current position of the cursor):
Should you need an interactive terminal, for example because you use the input
statement that requires the user to type things into the terminal, you must ensure your code is run on a worker:
<script type=\"py\" terminal worker>\nname = input(\"What is your name? \")\nprint(f\"Hello, {name}\")\n</script>\n
To use the interactive Python REPL in the terminal, use Python's code module like this:
import code\ncode.interact()\n
The end result should look something like this:
Finally, it is possible to dynamically pass Python code into the terminal. The trick is to get a reference to the terminal created by PyScript. Thankfully, this is very easy.
Consider this fragment:
<script id=\"my_script\" type=\"mpy\" terminal worker></script>\n
Get a reference to the element, and just call the process
method on that object:
const myterm = document.querySelector(\"#my_script\");\nawait myterm.process('print(\"Hello world!\")');\n
"},{"location":"user-guide/terminal/#xterm-reference","title":"XTerm reference","text":"Each terminal has a reference to the Terminal instance used to bootstrap the current terminal.
On the JavaScript side, it's a script.terminal
property while on the Python side, it's a __terminal__
special reference that guarantees to provide the very same script.terminal
:
<script id=\"py-terminal\" type=\"py\" terminal worker>\nfrom pyscript import document, ffi\n# example: change default font-family\n__terminal__.options = ffi.to_js({\"fontFamily\": \"cursive\"})\nscript = document.getElementById(\"py-terminal\")\nprint(script.terminal == __terminal__)\n# prints True with the defined font\n</script>\n
"},{"location":"user-guide/terminal/#clear-the-terminal","title":"Clear the terminal","text":"It's very simple to clear a PyTerminal:
Clearing the terminal<script type=\"mpy\" terminal worker>\nprint(\"before\")\n__terminal__.clear()\nprint(\"after\")\n# only \"after\" is on the terminal\n</script>\n
"},{"location":"user-guide/terminal/#terminal-colors","title":"Terminal colors","text":"Colors and most special characters work so you can make the text bold or turn it green. You could even use a control character to print('\\033[2J')
and clear the terminal, instead of using the exposed clear()
method:
<script type=\"mpy\" terminal worker>\nprint(\"This is \\033[1mbold\\033[0m\")\nprint(\"This is \\033[32mgreen\\033[0m\")\nprint(\"This is \\033[1m\\033[35mbold and purple\\033[0m\")\n</script>\n
"},{"location":"user-guide/terminal/#terminal-addons","title":"Terminal addons","text":"It's possible use XTerm.js addons:
Terminal addons<py-config>\n [js_modules.main]\n \"https://cdn.jsdelivr.net/npm/@xterm/addon-web-links/+esm\" = \"weblinks\"\n</py-config>\n<script type=\"py\" terminal>\nfrom pyscript import js_modules\naddon = js_modules.weblinks.WebLinksAddon.new()\n__terminal__.loadAddon(addon)\nprint(\"Check out https://pyscript.net/\")\n</script>\n
By default we enable the WebLinksAddon
addon (so URLs displayed in the terminal automatically become links). Behind the scenes is the example code shown above, and this approach will work for any other addon you may wish to use.
MicroPython has a very complete REPL already built into it.
Ctrl+X
strokes are handled, including paste mode and kill switches.tab
key to see available variables or objects in globals
.As a bonus, the MicroPython terminal works on both the main thread and in web workers, with the following caveats:
input
function are delegated to the native browser based prompt utility.while True:
loops). Such blocking code could freeze your page.input
function, without blocking the main thread.while True:
loops) does not block the main thread and your page will remain responsive.We encourage the usage of worker
attribute to bootstrap a MicroPython terminal. But now you have an option to run the terminal in the main thread. Just remember not to block!
PyScript is an open source platform for Python in the browser.
PyScript brings together two of the most vibrant technical ecosystems on the planet. If the web and Python had a baby, you'd get PyScript.
PyScript works because modern browsers support WebAssembly (abbreviated to WASM) - an instruction set for a virtual machine with an open specification and near native performance. PyScript takes versions of the Python interpreter compiled to WASM, and makes them easy to use inside the browser.
At the core of PyScript is a philosophy of digital empowerment. The web is the world's most ubiquitous computing platform, mature and familiar to billions of people. Python is one of the world's most popular programming languages: it is easy to teach and learn, used in a plethora of existing domains (such as data science, games, embedded systems, artificial intelligence, finance, physics and film production - to name but a few), and the Python ecosystem contains a huge number of popular and powerful libraries to address its many uses.
PyScript brings together the ubiquity, familiarity and accessibility of the web with the power, depth and expressiveness of Python. It means PyScript isn't just for programming experts but, as we like to say, for the 99% of the rest of the planet who use computers.
"},{"location":"user-guide/workers/","title":"Workers","text":"Workers run code that won't block the \"main thread\" controlling the user interface. If you block the main thread, your web page becomes annoyingly unresponsive. You should never block the main thread.
Happily, PyScript makes it very easy to use workers and uses a feature recently added to web standards called Atomics. You don't need to know about Atomics to use web workers, but it's useful to know that the underlying coincident library uses it under the hood.
Info
Sometimes you only need to await
in the main thread on a method in a worker when neither window
nor document
are referenced in the code running on the worker.
In these cases, you don't need any special header or service worker as long as the method exposed from the worker returns a serializable result.
"},{"location":"user-guide/workers/#http-headers","title":"HTTP headers","text":"To use the window
and document
objects from within a worker (i.e. use synchronous Atomics) you must ensure your web server enables the following headers (this is the default behavior for pyscript.com):
Access-Control-Allow-Origin: *\nCross-Origin-Opener-Policy: same-origin\nCross-Origin-Embedder-Policy: require-corp\nCross-Origin-Resource-Policy: cross-origin\n
If you're unable to configure your server's headers, you have two options:
service-worker
attribute with the script
element.For performance reasons, this is the preferred option so Atomics works at native speed.
The simplest way to use mini-coi is to copy the mini-coi.js file content and save it in the root of your website (i.e. /
), and reference it as the first child tag in the <head>
of your HTML documents:
<html>\n<head>\n<script src=\"/mini-coi.js\"></script>\n<!-- etc -->\n</head>\n<!-- etc -->\n</html>\n
"},{"location":"user-guide/workers/#option-2-service-worker-attribute","title":"Option 2: service-worker
attribute","text":"This allows you to slot in a custom service worker to handle requirements for synchronous operations.
Each <script type=\"m/py\">
or <m/py-script>
may optionally have a service-worker
attribute pointing to a locally served file (the same way mini-coi.js
needs to be served).
mini-coi.js
itself or any other custom service worker, as long as it provides either the right headers to enable synchronous operations via Atomics, or it enables sabayon polyfill events.window
and document
access in your worker logic.<html>\n<head>\n<!-- PyScript link and script -->\n</head>\n<body>\n<script type=\"py\" service-worker=\"./sw.js\" worker>\nfrom pyscript import window, document\ndocument.body.append(\"Hello PyScript!\")\n</script>\n</body>\n</html>\n
Warning
Using sabayon as the fallback for synchronous operations via Atomics should be the last solution to consider. It is inevitably slower than using native Atomics.
If you must use sabayon, always reduce the amount of synchronous operations by caching references from the main thread.
# \u274c THIS IS UNNECESSARILY SLOWER\nfrom pyscript import document\n# add a data-test=\"not ideal attribute\"\ndocument.body.dataset.test = \"not ideal\"\n# read a data-test attribute\nprint(document.body.dataset.test)\n# - - - - - - - - - - - - - - - - - - - - -\n# \u2714\ufe0f THIS IS FINE\nfrom pyscript import document\n# if needed elsewhere, reach it once\nbody = document.body\ndataset = body.dataset\n# add a data-test=\"not ideal attribute\"\ndataset.test = \"not ideal\"\n# read a data-test attribute\nprint(dataset.test)\n
In latter example the number of operations has been reduced from six to just four. The rule of thumb is: if you ever need a DOM reference more than once, cache it. \ud83d\udc4d
"},{"location":"user-guide/workers/#start-working","title":"Start working","text":"To start your code in a worker, simply ensure the <script>
, <py-script>
or <mpy-script>
tag pointing to the code you want to run has a worker
attribute flag:
<script type=\"py\" src=\"./my-worker-code.py\" worker></script>\n
You may also want to add a name
attribute to the tag, so you can use pyscript.workers
in the main thread to retrieve a reference to the worker:
<script type=\"py\" src=\"./my-worker-code.py\" worker name=\"my-worker\"></script>\n
from pyscript import workers\nmy_worker = await workers[\"my-worker\"]\n
Alternatively, to launch a worker from within Python running on the main thread use the pyscript.PyWorker class and you must reference both the target Python script and interpreter type:
Launch a worker from within Pythonfrom pyscript import PyWorker\n# The type MUST be given and can be either `micropython` or `pyodide`\nmy_worker = PyWorker(\"my-worker-code.py\", type=\"micropython\")\n
"},{"location":"user-guide/workers/#worker-interactions","title":"Worker interactions","text":"Code running in the worker needs to be able to interact with code running in the main thread and perhaps have access to the web page. This is achieved via some helpful builtin APIs.
Note
For ease of use, the worker related functionality in PyScript is a simpler presentation of more sophisticated and powerful behaviour available via PolyScript.
If you are a confident advanced user, please consult the XWorker related documentation from the PolyScript project for how to make use of these features.
To synchronise serializable data between the worker and the main thread use the sync
function in the worker to reference a function registered on the main thread:
from pyscript import PyWorker\ndef hello(name=\"world\"):\nreturn(f\"Hello, {name}\")\n# Create the worker.\nworker = PyWorker(\"./worker.py\", type=\"micropython\")\n# Register the hello function as callable from the worker.\nworker.sync.hello = hello\n
Python code in the resulting worker.from pyscript import sync, window\ngreeting = sync.hello(\"PyScript\")\nwindow.console.log(greeting)\n
Alternatively, for the main thread to call functions in a worker, specify the functions in a __export__
list:
import sys\ndef version():\nreturn sys.version\n# Define what to export to the main thread.\n__export__ = [\"version\", ]\n
Then ensure you have a reference to the worker in the main thread (for instance, by using the pyscript.workers
):
<script type=\"py\" src=\"./my-worker-code.py\" worker name=\"my-worker\"></script>\n
Referencing and using the worker from the main thread.from pyscript import workers\nmy_worker = await workers[\"my-worker\"]\nprint(await my_worker.version())\n
The values passed between the main thread and the worker must be serializable. Try the example given above via this project on PyScript.com.
No matter if your code is running on the main thread or in a web worker, both the pyscript.window
(representing the main thread's global window context) and pyscript.document
(representing the web page's document object) will be available and work in the same way. As a result, a worker can reach into the DOM and access some window
based APIs.
Warning
Access to the window
and document
objects is a powerful feature. Please remember that:
document
object, and other workers or code on the main thread does so too, they may interfere with each other and produce unforeseen problematic results. Remember, with great power comes great responsibility... and we've given you a bazooka (so please remember not to shoot yourself in the foot with it).While it is possible to start a MicroPython or Pyodide worker from either MicroPython or Pyodide running on the main thread, the most common use case we have encountered is MicroPython on the main thread starting a Pyodide worker.
Here's how:
index.html Evaluate main.py via MicroPython on the main thread
<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n<meta charset=\"utf-8\">\n<meta name=\"viewport\" content=\"width=device-width,initial-scale=1\">\n<!-- PyScript CSS -->\n<link rel=\"stylesheet\" href=\"https://pyscript.net/releases/2024.9.1/core.css\">\n<!-- This script tag bootstraps PyScript -->\n<script type=\"module\" src=\"https://pyscript.net/releases/2024.9.1/core.js\"></script>\n<title>PyWorker - mpy bootstrapping pyodide example</title>\n<script type=\"mpy\" src=\"main.py\"></script>\n</head>\n</html>\n
main.py MicroPython's main.py: bootstrapping a Pyodide worker.
from pyscript import PyWorker, document\n# Bootstrap the Pyodide worker, with optional config too.\n# The worker is:\n# * Owned by this script, no JS or Pyodide code in the same page can access\n# it.\n# * It allows pre-sync methods to be exposed.\n# * It has a ready Promise to await for when Pyodide is ready in the worker. \n# * It allows the use of post-sync (methods exposed by Pyodide in the\n# worker).\nworker = PyWorker(\"worker.py\", type=\"pyodide\")\n# Expose a utility that can be immediately invoked in the worker. \nworker.sync.greetings = lambda: print(\"Pyodide bootstrapped\")\nprint(\"before ready\")\n# Await until Pyodide has completed its bootstrap, and is ready.\nawait worker.ready\nprint(\"after ready\")\n# Await any exposed methods exposed via Pyodide in the worker.\nresult = await worker.sync.heavy_computation()\nprint(result)\n# Show the result at the end of the body.\ndocument.body.append(result)\n# Free memory and get rid of everything in the worker.\nworker.terminate()\n
worker.py The worker.py script runs in the Pyodide worker.
from pyscript import sync\n# Use any methods from main.py on the main thread.\nsync.greetings()\n# Expose any methods meant to be used from main.\nsync.heavy_computation = lambda: 6 * 7\n
Save these files in a tmp
folder, ensure your headers (just use npx mini-coi ./tmp
to serve via localhost) then see the following outcome in the browser's devtools.
before ready\nPyodide bootstrapped\nafter ready\n42\n
"}]}
\ No newline at end of file
diff --git a/2024.9.1/sitemap.xml.gz b/2024.9.1/sitemap.xml.gz
index 9a9e39b..294996b 100644
Binary files a/2024.9.1/sitemap.xml.gz and b/2024.9.1/sitemap.xml.gz differ
diff --git a/2024.9.1/user-guide/dom/index.html b/2024.9.1/user-guide/dom/index.html
index 079fe2c..721d618 100644
--- a/2024.9.1/user-guide/dom/index.html
+++ b/2024.9.1/user-guide/dom/index.html
@@ -1087,7 +1087,7 @@ pyscript.web