Skip to content

OpenSourceJesus/Py2Js

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

3 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Py2Js

A Python to optimized JavaScript translator inspired by PythonJS and Rusthon. It parses Python with the standard ast module and emits clean, fast JavaScript.

Features

  • Prototype-based classes — Python class and def __init__ become JS constructor + ClassName.prototype.method
  • Minimal runtime — Only a small __range() helper for range(); no heavy runtime
  • Built-in mappingsprintconsole.log, len(x)x.length, int/float/strNumber/String, etc.
  • List/dict literals — Native [] and {}
  • List/dict comprehensions — Transpiled to for...of loops with array/object accumulation
  • Control flowif/for/while/try/except with correct semantics (including for/while-else)

Install

From the project root:

pip install -e .

Or run without installing:

python -m py2js Examples/hello.py -o out.js

Usage

CLI

# 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)

Output style (PythonJS/Rusthon-like)

  • Classes: var ClassName = function(...) { this.__init__.apply(this, arguments); }; and ClassName.prototype.__init__ = function(...) { ... };
  • Methods: ClassName.prototype.methodName = function(...) { ... };
  • self: Omitted in JS; this is used as the instance

Supported Python constructs

  • Functions, async functions
  • Classes with __init__ and methods
  • Assignments (including tuple unpacking)
  • if / elif / else, for / while (with else and break/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)

References

  • PythonJS blog — Original Python→JS ideas and WebWorkers/Go backends
  • Rusthon blog — Fork with faster JS and benchmarks

License

MIT

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors