pscript Python to JavaScript Compiler
pscript is a Python-to-JavaScript compiler that allows developers to write Python code that runs directly in a JavaScript environment, such as a web browser or Node.js. It supports converting Python functions and basic data structures into their JavaScript equivalents, enabling seamless integration of Python logic into web applications. The current version is 0.8.1, with releases occurring periodically, often tied to Python version support updates.
Common errors
-
NameError: name 'document' is not defined
cause Attempting to use browser-specific JavaScript objects (like `document` or `window`) directly in the Python source code that is intended for transpilation, but trying to execute/evaluate that Python code without a JavaScript runtime.fixThe generated JavaScript code, not the Python source, is what interacts with browser APIs. Ensure the generated JavaScript is run in a browser or Node.js environment where `document` or `window` objects exist. The Python function definition itself should ideally remain abstract from the execution environment. -
TypeError: Cannot convert Python object of type <class 'MyCustomClass'> to JavaScript
cause pscript tries to transpile a Python object type that it doesn't recognize or know how to convert into a JavaScript equivalent (e.g., custom classes, complex library objects).fixOnly pass or operate on basic Python types (integers, floats, strings, booleans, lists, dictionaries, tuples) and simple functions. If custom objects are needed, convert them to supported primitive types (e.g., dictionaries) before passing them to `@pyscript`-decorated functions.
Warnings
- gotcha Only a subset of Python's standard library and built-in functions are supported for transpilation. Functions from modules like `os`, `sys`, or complex data structures are generally not translated.
- gotcha pscript generates JavaScript; it does not provide a JavaScript runtime in Python. Code relying on browser APIs (e.g., `document`, `window`) will only work when the generated JS is executed within a browser environment.
- gotcha Python's scoping rules, especially with closures and `nonlocal` variables, can behave subtly differently when transpiled to JavaScript. This can lead to unexpected variable capture.
Install
-
pip install pscript
Imports
- pyscript
from pscript import pyscript
- Script
from pscript import Script
Quickstart
from pscript import pyscript
@pyscript
def hello_js(name):
# This Python code will be transpiled to JavaScript
print(f'Hello, {name} from JavaScript!')
return f'Greetings, {name}'
# The generated JavaScript source code
js_code = hello_js.source
print(js_code)
# Example of using the generated function in a browser context (conceptual)
# You would typically inject js_code into an HTML <script> tag
# For example, in browser console:
# hello_js('World'); // Should print 'Hello, World from JavaScript!' to console