A Python to optimized JavaScript translator inspired by PythonJS and Rusthon. It parses Python with the standard ast module and emits clean, fast JavaScript.
- Prototype-based classes — Python
classanddef __init__become JS constructor +ClassName.prototype.method - Minimal runtime — Only a small
__range()helper forrange(); no heavy runtime - Built-in mappings —
print→console.log,len(x)→x.length,int/float/str→Number/String, etc. - List/dict literals — Native
[]and{} - List/dict comprehensions — Transpiled to
for...ofloops with array/object accumulation - Control flow —
if/for/while/try/exceptwith correct semantics (includingfor/while-else)
From the project root:
pip install -e .Or run without installing:
python -m py2js Examples/hello.py -o out.jsCLI
# stdin → stdout
python -m py2js < script.py
# file → file
python -m py2js script.py -o script.js
# Options
python -m py2js script.py -o script.js --no-runtime --indent " "API
from py2js import transpile
js = transpile("""
class Greeter:
def __init__(self, name):
self.name = name
def greet(self):
return "Hello, " + self.name + "!"
g = Greeter("World")
print(g.greet())
""")
print(js)- Classes:
var ClassName = function(...) { this.__init__.apply(this, arguments); };andClassName.prototype.__init__ = function(...) { ... }; - Methods:
ClassName.prototype.methodName = function(...) { ... }; self: Omitted in JS;thisis used as the instance
- Functions, async functions
- Classes with
__init__and methods - Assignments (including tuple unpacking)
if/elif/else,for/while(withelseandbreak/continue)try/except/finally,raise,assert- Expressions: literals, names, comparisons,
and/or/not, arithmetic, subscript, attribute, call - List/dict/tuple literals, list/dict comprehensions, lambda
print,range,len,int,float,str,list,dict,min,max,sum,abs- Imports are commented out (no runtime resolution)
- PythonJS blog — Original Python→JS ideas and WebWorkers/Go backends
- Rusthon blog — Fork with faster JS and benchmarks
MIT