javascripthon


Namejavascripthon JSON
Version 0.13 PyPI version JSON
download
home_pagehttps://github.com/azazel75/metapensiero.pj
SummaryJavascript for refined palates: a Python 3 to ES6 Javascript translator
upload_time2024-07-04 15:33:43
maintainerNone
docs_urlNone
authorAlberto Berti
requires_pythonNone
licenseGPLv3+
keywords javascript ecmascript compilation translation transpiling babel
VCS
bugtrack_url
requirements No requirements were recorded.
Travis-CI
coveralls test coverage No coveralls.
            .. -*- coding: utf-8 -*-
.. :Project:  metapensiero.pj -- readme
.. :Created:  mar 01 mar 2016 15:52:36 CET
.. :Author:   Alberto Berti <alberto@metapensiero.it>
.. :License:  GNU General Public License version 3 or later
..

======================================================
JavaScripthon: a Python 3 to ES6 JavaScript translator
======================================================

.. image:: https://gitlab.com/metapensiero/metapensiero.pj/badges/master/pipeline.svg
   :target: https://gitlab.com/metapensiero/metapensiero.pj/commits/master
   :align: left
   :alt: tests status

.. image:: https://gitlab.com/metapensiero/metapensiero.pj/badges/master/coverage.svg
   :target: https://gitlab.com/metapensiero/metapensiero.pj/commits/master
   :align: left
   :alt: tests coverage

.. image:: https://badges.gitter.im/javascripthon/Lobby.svg
   :alt: Join the chat at https://gitter.im/javascripthon/Lobby
   :target: https://gitter.im/javascripthon/Lobby?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge
   :align: left

.. figure:: http://s3.amazonaws.com/fossbytes.content/wp-content/uploads/2016/04/Javascripthon-python-js-converter.jpg
   :alt: JavaScripthon
   :align: left
   :width: 750px

   ..

   (image courtesy of `fossBytes`__)

   __ http://fossbytes.com/javascripthon-a-simple-python-to-es6-javascript-translator/


It is based on previous work by `Andrew Schaaf <andrew@andrewschaaf.com>`_.

 :author: Alberto Berti
 :contact: alberto@metapensiero.it
 :license: GNU General Public License version 3 or later

.. contents:: Table of Contents
   :backlinks: top

Introduction
------------

JavaScripthon is a small and simple Python 3.5+ translator to JavaScript which
aims to be able to translate most of the Python's core semantics without
providing a full python-in-js environment, as most existing translators do. It
tries to emit code which is simple to read and check. It does so by switching
to ES6 construct when possible/required. This allows to simplify the needs of
polyfills for many of the expected Python behaviors.

It is designed to be the first step in a pipeline that translates your Python
code into something that a browser can understand. Usually it is used with
tools like `BabelJS`__ and `Webpack`__ to prepare the final bundle that will
be served to the browser. The steps from the source code to the bundle are the
following:

1) JavaScripthon converts your Python 3.5+ code to ES6 JavaScript modules;
2) the BabelJS loader (configured inside Webpack or standalone) translates the
   ES6 JavaScript to ES5 so that the browser can understand it;
3) Webpack parses the resulting source code and packages your source code with
   its dependencies by analyzing ``import`` statements and emits a
   ``bundle.js`` ready to be served to the browser.

Along this process the corresponding `source maps`__ are read and integrated at
every step, allowing you to place breakpoints on your original Python source
files when working with the developer tools of your browser.

An example of such setup is provided in the ``examples`` directory.

__ http://babeljs.io/
__ http://webpack.github.io/
__ http://blog.teamtreehouse.com/introduction-source-maps


In addition to that, you can choose to do most these steps without using
external JS tools. It comes with an `embedded js interpreter`__ that loads a
standalone version of BabelJS and converts your code to ES5 JavaScript without
the need to install anything else. In fact most of the the test you can find
in ``tests/test_evaljs.py`` use the embedded interpreter to dual evaluate the
source code (one time in Python, one time in JavaScript) and simply check that
the results are the same.

__ https://github.com/amol-/dukpy

Thanks to that, JavaScripthon can also be used as a server-side library to
translate single functions or classes that you want your browser to load and
evaluate.

The interface with the JS world is completely flat, just import the modules
or use the expected globals (``window``, ``document``, etc...) as you
would do in JavaScript.

Brief list of the supported Python semantics
--------------------------------------------

The fact that JavaScripthon doesn't *reinvent the wheel* by reimplementing in
Python many of the features available with JavaScript translators/transpilers
allows it to be lean while implementing quite a decent set of the core Python
semantics. These are, briefly:

* Misc

  - list slices;
  - list's ``append()``;
  - dict's ``copy()``, ``update()``;
  - ``len()``;
  - ``print()``;
  - ``str()``;
  - ``type(instance)``;
  - ``yield`` and ``yield from``;
  - ``async`` and ``await``;
  - ``import`` and ``from...import`` to use any JS module (see `import
    statements`_);
  - ``callable()``;
  - ``hasattr()``, ``getattr()``, ``setattr()``;
  - template literals with ``tmpl('a string with ${substitution}')``;
  - simple Python 3.6+ `f-strings`_ (see `Strings`_);
  - template literals and tagged_templates (see `Strings`_);
  - names starting with ``d_`` and ``dd_`` will have that part replaced with
    ``$`` and ``$$``, respectively;
  - names ending with an underscore will have it removed. Useful for example
    with the AVA ES6 test runner which has a check named ``is``;
  - ``__instancecheck__`` to ``[Symbol.hasInstance]``;
  - ``int`` to ``parseInt``;
  - ``float`` to ``parseFloat``;
  - dictionary keys are unambiguous when ES6 translation is
    enabled. For example the following code gets translated correctly:

    .. code:: python

       a = 'foo'
       d = {a: 1}
       print(d[a])

    prints ``1`` in both Python and JavaScript, while it prints
    ``undefined`` when translated and evaluated in JavaScript without
    ES6.

.. _f-strings: https://docs.python.org/3.6/reference/lexical_analysis.html#f-strings

* Comparisons (see section `Simple stuff`_ for the details)

  - most of the basics;
  - ``isinstance()`` and ``issubclass()``;
  - ``element in container`` for use with lists, objects, strings and the new
    ES6 collections like ``Map``, ``Set`` and so on;
  - identity checks: ``foo is bar``;
  - chained comparisons like ``x < y <= z``;

* Statements (see section `Simple stuff`_ and `for statement`_ for the
  details)

  - ``if...elif...else``;
  - ``while`` loop;
  - ``for`` over list, over range, over plain js objects, over iterables (JS
    iterables);
  - ``try...except...finally`` with pythonesque behavior (see
    `try...except...finally statement`_ section for the details);
  - ``assert`` statement;

* Functions (see `Functions`_ section)

  - standard functions, generator functions, async functions;
  - parameters defaults;
  - keyword parameters;
  - parameters accumulators (``*args`` and ``**kwargs``), with some
    restrictions;
  - functions in methods are usually converted to "arrow functions" (the new
    ES6 syntax like ``(foo, bar) => foo * bar;``) because they automatically
    keep ``this`` from the enclosing scope. Appending ``_fn`` to a function
    declaration will force the translation to a normal function;

* Classes (see `Classes`_ section)

  - single inheritance;
  - Exception classes for use with ``except`` statement;
  - class decorators and method decorators;
  - property descriptors;
  - special handling of ``property`` and ``classmethod`` descriptors;
  - async methods, generator methods;
  - non-function body members (i.e. ``member_of_class_Foo = bar``);

License
-------

This package is covered by the `GNU General Public License version
3 or later`__. The code produced by it (i.e. the transpiled
JavaScript) is *your* code, and *you* are free to choose whatever
license you like. The only ``runtime`` that exists is the file
`snippets.py`__ from which some utility functions are picked when
necessary and transpiled together with your code. While it's
distributed with the same license as the other source code, in its
*transpiled* form will have the license you choose.

So, to summarize, the license of the this tool is GPL, but it doesn't
extends to the products of this tool, on which you are free to decide.

__ https://www.gnu.org/licenses/gpl.html
__ https://github.com/azazel75/metapensiero.pj/blob/master/src/metapensiero/pj/snippets.py

Installation
------------

Python 3.5 is required because Python's AST has changed between 3.4
and 3.5 and as of now supporting multiple Python versions is not one
of my priorities.

To install the package execute the following command::

  $ pip install javascripthon

or, if you want install it from sources::

  $ git clone https://github.com/azazel75/metapensiero.pj
  $ pip install -r metapensiero.pj/requirements.txt
  $ pip install metapensiero.pj

Usage
-----

To *compile* or *transpile* a python source module, use the
commandline:

.. code:: bash

  $ python -m metapensiero.pj source.py

or:

.. code:: bash

  $ python -m metapensiero.pj -5 source.py

to transpile.

A ``pj`` console script is also automatically installed:

.. code:: bash


  $ pj --help
  usage: pj [-h] [--disable-es6] [--disable-stage3] [-5] [--transform-runtime]
            [-o OUTPUT] [-d] [--pdb] [-s STRING] [-e]
            [file [file ...]]

  A Python 3.5+ to ES6 JavaScript compiler

  positional arguments:
    file                  Python source file(s) or directory(ies) to convert.
                          When it is a directory it will be converted
                          recursively

  optional arguments:
    -h, --help            show this help message and exit
    --disable-es6         Disable ES6 features during conversion (Ignored if
                          --es5 is specified)
    --disable-stage3      Disable ES7 stage3 features during conversion
    -5, --es5             Also transpile to ES5 using BabelJS.
    --transform-runtime   Add trasform runtime as plugin during transpile
    -o OUTPUT, --output OUTPUT
                          Output file/directory where to save the generated code
    -d, --debug           Enable error reporting
    --pdb                 Enter post-mortem debug when an error occurs
    -s STRING, --string STRING
                          Convert a string, useful for small snippets. If the
                          string is '-' will be read from the standard input.
    -e, --eval            Evaluate the string supplied with the -s using the
                          embedded interpreter and return the last result. This
                          will convert the input string with all the extensions
                          enabled (comparable to adding the '-5' option) and so
                          it will take some time because of BabelJS load times.

This offers many ways to test the framework, both the string conversion and
the evaluation using the embedded JavaScript interpreter are very handy. For
example:

.. code:: bash

  $ pj -s '"foo" if True else "bar"'
  (true ? "foo" : "bar");

and evaluating the same statement:

.. code:: bash

  $ pj -s '"foo" if True else "bar"' -e
  foo

You can even try more fancy ES6 features, like destructuring assignment:

.. code:: bash

   $ pj -s "a, b, c = (2, 3, 5) \na+b+c" -e
   10

You can use metapensiero.pj in python code as well.

.. code:: python

    from metapensiero.pj.__main__ import transform_string

    transform_string("print()")

Reporting Bugs
--------------

The main development repository is the one on gitlab__, the one on
github is just a mirror so please report issues and feature requests
there__.

__ https://gitlab.com/metapensiero/metapensiero.pj
__ https://gitlab.com/metapensiero/metapensiero.pj/issues

Conversions Rosetta Stone
-------------------------

Here is a brief list of examples of the conversions the tool applies,
just some, but not all.

Simple stuff
~~~~~~~~~~~~

.. list-table:: Most are obvious
  :header-rows: 1

  * - Python
    - JavaScript

  * - .. code:: python

        x < y <= z < 5

    - .. code:: javascript

        ((x < y) && (y <= z) && (z < 5))

  * - .. code:: python


        def foo():
            return [True, False, None, 1729,
                    "foo", r"foo\bar", {}]

    - .. code:: javascript

        function foo() {
            return [true, false, null, 1729,
                    "foo", "foo\\bar", {}];
        }


  * - .. code:: python

        while len(foo) > 0:
            print(foo.pop())

    - .. code:: javascript

        while ((foo.length > 0)) {
            console.log(foo.pop());
        }


  * - .. code:: python

        if foo > 0:
            ....
        elif foo < 0:
            ....
        else:
            ....

    - .. code:: javascript

        if ((foo > 0)) {
            ....
        } else {
            if ((foo < 0)) {
                ....
            } else {
                ....
            }
        }


  * - .. code:: python

        str(x)

    - .. code:: javascript

        x.toString()

  * - .. code:: python

        yield foo
        yield from foo

    - .. code:: javascript

        yield foo
        yield* foo


Then there are special cases. Here you can see some of these
conversions. JavaScripthon cannot do a full trace of the sources, so
some shortcuts are taken about the conversion of some core, specific
Python's semantics. For example Python's ``self`` is always converted
to JavaScript's ``this``, no matter where it's found. Or ``len(foo)``
is always translated to ``foo.length``. Albeit this an API specific of
just some objects (Strings, Arrays, etc...), it is considered wide
adopted and something the user may consider obvious.

The rules of thumb to treat things especially are:

* Is it possible to think of a conversion that covers most of the use
  cases?

* Is ts possible to find a convention widely used on the Python world
  to express this special case?

.. list-table:: There are special cases
  :header-rows: 1

  * - Python
    - JavaScript

  * - .. code:: python

        ==

    - .. code:: javascript

        ===

  * - .. code:: python

        !=

    - .. code:: javascript

        !==

  * - .. code:: python

        2**3

    - .. code:: javascript

        Math.pow(2, 3)

  * - .. code:: python

        'docstring'

    - .. code:: javascript

        /* docstring */

  * - .. code:: python

        self

    - .. code:: javascript

        this

  * - .. code:: python

        len(...)

    - .. code:: javascript

        (...).length

  * - .. code:: python

        print(...)

    - .. code:: javascript

        console.log(...)

  * - .. code:: python

        isinstance(x, y)
        isinstance(x, (y, z))

    - .. code:: javascript

        (x instanceof y)
        (x instanceof y || x instanceof z)

  * - .. code:: python

        typeof(x)

    - .. code:: javascript

        (typeof x)

  * - .. code:: python

        type(x)

    - .. code:: javascript

        Object.getPrototypeOf(x)

  * - .. code:: python

        FirstCharCapitalized(...)
        new(any_function(...))

    - .. code:: javascript

        new FirstCharCapitalized(...)
        new any_function(...)

  * - .. code:: python

        foo in bar

    - .. code:: javascript

        var _pj;
        function _pj_snippets(container) {
            function in_es6(left, right) {
                if (((right instanceof Array) || ((typeof right) === "string"))) {
                    return (right.indexOf(left) > (- 1));
                } else {
                    if (((right instanceof Map) || (right instanceof Set)
                        || (right instanceof WeakMap)
                        || (right instanceof WeakSet))) {
                        return right.has(left);
                    } else {
                        return (left in right);
                    }
                }
            }
            container["in_es6"] = in_es6;
            return container;
        }
        _pj = {};
        _pj_snippets(_pj);
        _pj.in_es6(foo, bar);

  * - .. code:: python

        foo[3:]
        foo[:3]

    - .. code:: javascript

        foo.slice(3);
        foo.slice(0, 3);

  * - .. code:: python

        list(foo).append(bar)

    - .. code:: javascript

        foo.push(bar);

  * - .. code:: python

        dict(foo).update(bar)

    - .. code:: javascript

        Object.assign(foo, bar);

  * - .. code:: python

        dict(foo).copy()

    - .. code:: javascript

        Object.assign({}, foo);


``for`` statement
~~~~~~~~~~~~~~~~~

The ``for`` statement by default is translated as if the object of the
cycle is a list but has two special cases:


.. list-table:: ``for`` loops
  :header-rows: 1

  * - Python
    - JavaScript
    - notes

  * - .. code:: python

        for el in dict(a_dict):
            print(el)

    - .. code:: javascript

        var _pj_a = a_dict;
        for (var el in _pj_a) {
            if (_pj_a.hasOwnProperty(el)) {
                console.log(el);
            }
        }

    - With this kind of loop if you use ``dict(a_dict, True)`` the check on
      ``hasOwnProperty()`` will not be added, so the loop will include
      *inherited* (and *enumerable*) properties.

  * - .. code:: python

        for el in an_array:
            print(el)

    - .. code:: javascript

        for (var el, _pj_c = 0, _pj_a = an_array, _pj_b = _pj_a.length;
              (_pj_c < _pj_b); _pj_c += 1) {
            el = _pj_a[_pj_c];
            console.log(el);
        }

    -

  * - .. code:: python

        for i in range(5):
            print(i)

    - .. code:: javascript

        for (var i = 0, _pj_a = 5; (i < _pj_a); i += 1) {
            console.log(i);
        }

    -

  * - .. code:: python

        for el in iterable(a_set):
            print(el)

    - .. code:: javascript

        var _pj_a = a_set;
        for (var el of  _pj_a) {
            console.log(el);
        }

    - This will loop over all the iterables, like instances of ``Array``,
      ``Map``, ``Set``, etc. **but not over normal objects**.

Functions
~~~~~~~~~

Functions are very well supported. This should be obvious, you can say. Really
it is not so simple, if we mean functions in their broader meaning, including
the  *async functions* and *generator functions*.

.. list-table:: The various types of functions at play
  :header-rows: 1

  * - Python
    - JavaScript
    - notes

  * - .. code:: python

        def foo(a, b, c):
            pass

    - .. code:: javascript

        function foo(a, b, c) {
        }

    - Normal functions

  * - .. code:: python

        def foo(a, b, c):
            for i in range(a, b, c):
                yield i

        for i in iterable(foo(0, 5, 2)):
            print(i)

    - .. code:: javascript

        function* foo(a, b, c) {
            for ... { // loop control omitted for brevity
                yield i;
            }
        }

        for (var i of foo(0, 5, 2)) {
            console.log(i);
        }

    - Generator functions. They return an iterable and to correctly loop over
      it you should use the ``iterable(...)`` call, so that the Python's
      ``for...in`` will be converted into a ``for...of``

  * - .. code:: python

        async def foo(a, b, c):
            await some_promise_based_async


    - .. code:: javascript

        async function foo(a, b, c) {
            await some_promised_base_async;
        }

    - Async functions. They make use of the new ``Promise`` class, which is
      also available.


Function's args and call parameters
+++++++++++++++++++++++++++++++++++

Parmeters defaults and keyword parameters are supported and so is ``*foo``
accumulator, which is translated into the ES6 rest expression (``...foo``).

The only caveat is that JS support for keyword args sucks, so you will have to
**remember to fill in all the arguments before specifying keywords**.

On function definitions, ``**kwargs`` is supported if it's alone, i.e. without
either keyword arguments or ``*args``.

.. list-table:: function's args and call parameters
  :header-rows: 1

  * - Python
    - JavaScript

  * - .. code:: python

        def foo(a=2, b=3, *args):
            pass

    - .. code:: javascript

        function foo(a = 2, b = 3, ...args) {
        }

  * - .. code:: python

        def bar(c, d, *, zoo=2):
            pass

    - .. code:: javascript

        function bar(c, d, {zoo = 2}={}) {
        }

  * - .. code:: python

        foo(5, *a_list)

    - .. code:: javascript

        foo(5, ...a_list);

  * - .. code:: python

        bar('a', 'b', zoo=5, another='c')

    - .. code:: javascript

        bar("a", "b", {zoo: 5, another: "c"});

  * - .. code:: python

        def zoo(e, **kwargs):
            print(kwargs['bar'])

    - .. code:: javascript

        function zoo(e, kwargs = {}) {
            console.log(kwargs['bar'])
        }

  * - .. code:: python

        zoo(4, bar=6)

    - .. code:: javascript

        zoo(4, {bar: 6})

Classes
~~~~~~~

Classes are translated to ES6 classes as much as they can support. This means:

* no direct support multi-class inheritance, you have to come up with your own
  solution for now. Many established frameworks support this in a way or
  another so just use those facilities for now. I've read of some attempts,
  see for example the suggestion on `Mozilla developer`__ or the other about
  `simple mixins`__ on ``Exploring ES6``.

* external implementation for class-level non assignment members. Assignment
  members are those on the body of a class which are defined with: ``a_label =
  an_expression`` like:

  .. code:: python

    class Foo:

        bar = 'zoo' # or any kind of expression

  These members are removed from the translated body and submitted to a
  snippet of code that will run after class creation in JS land. This serves
  two purposes: if the value is *simple*, i.e. it isn't an instance of
  ``Object``, it will be setup as a *data descriptor*, and it will work mostly
  like you are used to in Python. The most noticeable caveat is that it will
  not be accessible through the class as it is in Python, you will have to
  access the class' *prototype*, so in the case above i mean
  ``Foo.prototype.bar``.

  The other purpose is to check for *accessor descriptors*. If the value on
  the right side of the assignment implements a ``get`` function, it will be
  installed as a property as-is, and its *get* and *set* members will be used
  to manage the value with the ``bar`` name.

* external implementation for method decorators whose name is different from
  ``property`` or ``classmethod`` (more on these later on), because these are
  already supported by the ES6 class notation.

* external implementation for class decorators. One caveat here is that the
  return value of the decorator has always to be a function with a prototype:
  unfortunately a ``new`` statement seems not to be *delegable* in any way. So
  for example a class decorator implemented like the following:

  .. code:: python

    def test_class_deco():

        counter = 0

        def deco(cls):
            def wrapper(self, *args):
                counter += 1 # side effect
                return cls(*args)
            return wrapper

        @deco
        class Foo:
            pass

  will never work. This will work instead:

  .. code:: python

    def deco(cls):
        def wrapper(self, *args):
            counter += 1 # side effect
            return cls.prototype.constructor.call(self, *args)
        wrapper.prototype = cls.prototype
        return wrapper

  So either return the original class or setup the wrapper appropriately.


__ https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes#Mix-ins
__ http://exploringjs.com/es6/ch_classes.html#_simple-mixins


Methods can be functions or async-functions although the latters aren't
officially supported yet by the JavaScript specification. You can disable them
adding a ``--disable-stage3`` to the command line utility.

Python`s ``super()`` calls are converted accordingly to the type of
their surrounding method: ``super().__init__(foo)`` becomes
``super(foo)`` in constructors.

Functions inside methods are translated to arrow functions so that
they keep the ``this`` of the surrounding method.

``@property`` and ``@a_property.setter`` are translated to ES6 properties.

Methods decorated with ``@classmethod`` are translated to ``static`` methods.

Special methods ``__str__`` and ``__len__`` are translated to
``toString()`` method and ``get length()`` property, respectively.

Arrow method expression to retain the ``this`` at method level aren't
implemented yet.


.. list-table:: Classes
  :header-rows: 1

  * - Python
    - JavaScript

  * - .. code:: python

        class Foo(bar):
            def __init__(self, zoo):
                super().__init__(zoo)


            def meth(self, zoo):
                super().meth(zoo)
                def cool(a, b, c):
                    print(self.zoo)


            async def something(self, a_promise):
                result = await a_promise

            def generator_method(self):
                yield something

            @property
            def foo(self):
                return self._foo


            @foo.setter
            def foo(self, value):
                self._foo = value


            @classmethod
            def bar(self, val):
                do_something()


            def __len__(self):
                return 1


            def __str__(self):
                return 'Foo instance'

    - .. code:: javascript

        class Foo extends bar {
            constructor(zoo) {
                super(zoo);
            }

            meth(zoo) {
                super.meth(zoo);
                var cool;
                cool = (a, b, c) => {
                    console.log(this.zoo);
                };
            }

            async something(a_promise) {
                var result;
                result = await a_promise;
            }

            * generator_method() {
                yield something;
            }

            get foo() {
                return this._foo;
            }

            set foo(value) {
                self._foo = value;
            }

            static bar(val) {
                do_something()
            }

            get length() {
                return 1;
            }

            toString() {
                return "Foo instance";
            }
        }

Only direct descendants of ``Exception`` are treated especially, but
just for them to be meaningful in JS land and to be detectable with
``instanceof`` in catch statements.


.. list-table:: Exceptions
  :header-rows: 1

  * - Python
    - JavaScript

  * - .. code:: python

        class MyError(Exception):
            pass

        raise MyError("An error occurred")

    - .. code:: javascript

        function MyError(message) {
            this.name = "MyError";
            this.message = (message || "Custom error MyError");
            if (((typeof Error.captureStackTrace) === "function")) {
                Error.captureStackTrace(this, this.constructor);
            } else {
                this.stack = new Error(message).stack;
            }
        }
        MyError.prototype = Object.create(Error.prototype);
        MyError.prototype.constructor = MyError;
        throw new MyError("An error occurred");


``try...except...finally`` statement
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

The conversion of this statement is mostly obvious with the only
exception of the ``except`` part: it translates to a ``catch`` part
containing one ``if`` statement for each non catchall ``except``. If a
catchall ``except`` isn't present, the error will be re-thrown, to mimic
Python's behavior.

.. list-table:: ``try...catch...finally`` statement
  :header-rows: 1

  * - Python
    - JavaScript

  * - .. code:: python

        try:
            foo.bar()
        except MyError:
            recover()
        except MyOtherError:
            recover_bad()
        finally:
            foo.on_end()

    - .. code:: javascript

        try {
            foo.bar();
        } catch(e) {
            if ((e instanceof MyError)) {
                recover();
            } else {
                if ((e instanceof MyOtherError)) {
                    recover_bad()
                } else {
                    throw e;
                }
            }
        } finally {
            foo.on_end();
        }


``import`` statements
~~~~~~~~~~~~~~~~~~~~~

``import`` and ``from ... import`` statements are converted to ES6
imports, and the declaration of an ``__all__`` member on the module
top level is translated to ES6 named exports.

.. list-table:: import and exports
  :header-rows: 1

  * - Python
    - JavaScript

  * - .. code:: python

        import foo, bar
        import foo.bar as b
        from foo.bar import hello as h, bye as bb
        from ..foo.zoo import bar
        from . import foo
        from .foo import bar

        from foo__bar import zoo

        from __foo.zoo import bar

        from foo import __default__ as bar

        from __globals__ import test_name

        # this should not trigger variable definition
        test_name = 2

        # this instead should do it
        test_foo = True

        __all__ = ['test_name', 'test_foo']
        __default__ = 'test_name'

    - .. code:: javascript

        var test_foo;

        import * as foo from 'foo';
        import * as bar from 'bar';
        import * as b from 'foo/bar';
        import {hello as h, bye as bb} from 'foo/bar';
        import {bar} from '../foo/zoo';
        import * as foo from './foo';
        import {bar} from './foo';

        import {zoo} from 'foo-bar';

        import {bar} from '@foo/zoo';

        import bar from 'foo';

        test_name = 2;
        test_foo = true;

        export {test_name, test_foo};
        export default test_name;

About JS **default** ``export`` and ``import``
++++++++++++++++++++++++++++++++++++++++++++++

If you want to export something as *default export* in your modules,
declare a ``__default__`` member and assign to it the string of the
symbol you want to export. To clarify:

.. code:: python

  foo = 42
  bar = "hello"

  __all__ = ['foo', 'bar']  # foo and bar will be exported as named exports
  __default__ = 'bar'  # bar will also be exported as the *default*

This becomes:

.. code:: javascript

  var bar, foo;

  foo = 42;
  bar = "hello";

  export {foo, bar};
  export default bar;

For what concerns the ``import``, you can import the default export of
a module using the ``default`` name, as defined by the ES6
spec. However, as there were some issues reported to me with bundlers
not supporting the named import of the default export, a special
``import`` statement using ``__default__ as name`` has been added that
directly translates to the more common form of ES6 default import. So:

.. code:: python

  from foo import default as bar
  from foo import __default__ as zoo

Translates to:

.. code:: javascript

  import {default as bar} from 'foo';
  import zoo from 'foo';

The two imports should work the same, see `exploring js section`__ and
the linked spec. But if you encounter problems with the former use
the latter instead. Keep in mind that you cannot mix the
``__default__`` import with others (i.e. it needs to be on a line of
its own) and that you always need to specify an ``... as name ...`` part.

__ http://exploringjs.com/es6/ch_modules.html#sec_importing-exporting-details

Strings
-------

Javascripthon supports converting Python 3.6+ `f-strings`_ to ES6
`template literals`_. The expression in the braces gets converted, but
neither `conversion`__ nor `format_spec`__ are supported: ``f"Value of
{a}"`` becomes ```Value of ${a}``` and ``f"Value of {self.foo}"``
becomes ```Value of ${this.foo}```.

.. _template literals: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals
__ https://docs.python.org/3.6/reference/lexical_analysis.html#grammar-token-conversion
__ https://docs.python.org/3.6/reference/lexical_analysis.html#grammar-token-format_spec

You can also write *raw* template literals by using the function
``tmpl()`` it does only a conversion of the string markers, from those
used in Python's literal string notation to template literal notation.

There is also the way to express *tagged templates*, template literals
that are parsed using a provided function. This is done by using the
function ``__``. So for example:

.. code:: python

  __('A template ${string} with foo', bar)

gets translated to:

.. code:: javascript

  bar`A template ${string} with foo`

``bar`` will be executed with the value of ``${string}`` as a
parameter, see the link for `template literals`_ for help.

Verbatim JS
-----------

You can intermix Python and JS by using the
``JS('Your-JS-code-here')`` marker function. It will not be touched by
the ES6 transcoder but if you choose to also transpile it to ES5, il
will be considered by Babel.


Examples
--------

Execute ``make`` inside the ``examples`` directory.

Testing
-------

To run the tests you should run the following at the package root::

  python setup.py test

How to contribute
-----------------

So you like this project and want to contribute? Good!

These are the terse guidelines::

  There are some TODO points in the readme, or even the issue #6 is
  quite simple to fix. Feel free to pick what you like.

  The guidelines are to follow PEP8 for coding where possible, so use
  CamelCase for classes and snake_case for variables, functions and
  members, and UPPERCASE for constants.

  An exception to this rules are the function names inside
  ``metapensiero.pj.transformations`` subpackage. Those are matched
  against names of the AST objects coming from the ``ast`` module in
  standard lib, so they have to to match even in case.

  Try to keep lines lengths under 79 chars, more or less ;-)

  The workflow is to fork the project, do your stuff, maybe add a test
  for it and then submit a pull request.

  Have fun

Contributing
------------

Any contribution is welcome, drop me a line or file a pull request.

External contributions
----------------------

* `BrainBacon`__ has made a `JavaScripthon loader`__ for WebPack;

* `icarito`_ has contributed support for JavaScripthon to the
  `python-webpack-loader`__ for WebPack (Every valid JS package has at
  least two implementations! ROTFL);

* `icarito`_ has also `integrated JavaScripthon with Nuxt.js and
  Vue.js`__;

* `chfw`__ has integrated `JavaScripthon into pyecharts`__ to allow
  Python function translation.

.. _icarito: https://github.com/icarito
__ https://github.com/BrainBacon
__ https://github.com/Beg-in/javascripthon-loader
__ https://github.com/martim00/python-webpack-loader
__ https://nuxt-python.surge.sh/
__ https://github.com/chfw
__ https://github.com/pyecharts/pyecharts

Todo
----

This is a brief list of what needs to be done:

* refactor the comprehensions conversion to use the snippets facility;
* refactor snippets rendering to write them as a module and import
  them in the module when tree conversion is enabled;
* convert ``dict()`` calls to ES6 ``Map`` object creation;
* convert *set* literals to ES6 ``Set`` objects. Also, update
  "foo in bar" to use bar.has(foo) for sets;

Done
----

Stuff that was previously in the todo:

* translate *import* statements to ES6;
* translate ``__all__`` definition to ES6 module exports;
* write a command line interface to expose the api;
* make try...except work again and implement try...finally;
* convert *async* and *await* to the same proposed features for js
  (see BabelJS documentation);
* convert argument defaults on functions to ES6;
* convert call keyword arguments;
* convert `*iterable` syntax to ES6 destructuring;
* use arrow functions for functions created in functions;
* properties to ES6 properties (getter and setter);
* take advantage of new duckpy features to use a JS execution context
  that lasts multiple calls. This way the BabelJS bootstrap affects
  only the initial execution;
* class and method decorators;
* implement *yield*, *yield from* and generator functions;
* update "foo in bar" to use bar.has(foo) for maps;


External documentation
----------------------

A good documentation and explanation of ES6 features can be found on
the book `Exploring ES6`__ by Axel Rauschmayer (donate if you can).

__ http://exploringjs.com/es6/

An `extensive documentation`__ about Python's AST objects, very handy.

__ https://greentreesnakes.readthedocs.org/en/latest/

Tools
-----

Have a look at `ECMAScript 6 Tools`__ by Addy Osmani.

__ https://github.com/addyosmani/es6-tools

To debug *source maps* have a look at `source-map-visualization`__ and
its `package`__ on npm.

__ https://sokra.github.io/source-map-visualization/
__ https://www.npmjs.com/package/source-map-visualize

Still i found these links to be helpful:

* `BASE64 VLQ CODEC (COder/DECoder)`__
* `Testing Source Maps`__

__ http://murzwin.com/base64vlq.html
__ http://fitzgeraldnick.com/2013/08/02/testing-source-maps.html

Here is an `example`__ of the latter tool showing code generated by
JavaScripthon, have fun!

__ https://sokra.github.io/source-map-visualization/#base64,ZnVuY3Rpb24gc2ltcGxlX2FsZXJ0KCkgewogICAgd2luZG93LmFsZXJ0KCJIaSB0aGVyZSEiKTsKfQpmdW5jdGlvbiBhdHRhY2hfaGFuZGxlcigpIHsKICAgIHZhciBlbDsKICAgIGVsID0gZG9jdW1lbnQucXVlcnlTZWxlY3RvcigiYnV0dG9uIik7CiAgICBlbC5hZGRFdmVudExpc3RlbmVyKCJjbGljayIsIHNpbXBsZV9hbGVydCk7Cn0KYXR0YWNoX2hhbmRsZXIoKTsKCi8vIyBzb3VyY2VNYXBwaW5nVVJMPWh0bWxfdGVzdC5qcy5tYXAK,eyJtYXBwaW5ncyI6IkFBT0E7SUFDSUEsTUFBQUMsTUFBQSxDQUFhLFdBQWI7QUFESjtBQUdBOztJQUNJQyxLQUFLQyxRQUFBQyxjQUFBLENBQXVCLFFBQXZCO0lBQ0xGLEVBQUFHLGlCQUFBLENBQW9CLE9BQXBCLEVBQTZCQyxZQUE3QjtBQUZKO0FBSUFDLGNBQUEiLCJzb3VyY2VzIjpbImh0bWxfdGVzdC5weSJdLCJ2ZXJzaW9uIjozLCJuYW1lcyI6WyJ3aW5kb3ciLCJ3aW5kb3cuYWxlcnQiLCJlbCIsImRvY3VtZW50IiwiZG9jdW1lbnQucXVlcnlTZWxlY3RvciIsImVsLmFkZEV2ZW50TGlzdGVuZXIiLCJzaW1wbGVfYWxlcnQiLCJhdHRhY2hfaGFuZGxlciJdLCJzb3VyY2VzQ29udGVudCI6WyIjIC0qLSBjb2Rpbmc6IHV0Zi04IC0qLVxuIyA6UHJvamVjdDogIHBqIC0tIHRlc3QgZm9yIGh0bWxcbiMgOkNyZWF0ZWQ6ICAgIG1hciAwMSBtYXIgMjAxNiAyMzo0ODo1MiBDRVRcbiMgOkF1dGhvcjogICAgQWxiZXJ0byBCZXJ0aSA8YWxiZXJ0b0BtZXRhcGVuc2llcm8uaXQ+XG4jIDpMaWNlbnNlOiAgIEdOVSBHZW5lcmFsIFB1YmxpYyBMaWNlbnNlIHZlcnNpb24gMyBvciBsYXRlclxuI1xuXG5kZWYgc2ltcGxlX2FsZXJ0KCk6XG4gICAgd2luZG93LmFsZXJ0KCdIaSB0aGVyZSEnKVxuXG5kZWYgYXR0YWNoX2hhbmRsZXIoKTpcbiAgICBlbCA9IGRvY3VtZW50LnF1ZXJ5U2VsZWN0b3IoJ2J1dHRvbicpXG4gICAgZWwuYWRkRXZlbnRMaXN0ZW5lcignY2xpY2snLCBzaW1wbGVfYWxlcnQpXG5cbmF0dGFjaF9oYW5kbGVyKClcbiJdfQ==,IyAtKi0gY29kaW5nOiB1dGYtOCAtKi0KIyA6UHJvamVjdDogIHBqIC0tIHRlc3QgZm9yIGh0bWwKIyA6Q3JlYXRlZDogICAgbWFyIDAxIG1hciAyMDE2IDIzOjQ4OjUyIENFVAojIDpBdXRob3I6ICAgIEFsYmVydG8gQmVydGkgPGFsYmVydG9AbWV0YXBlbnNpZXJvLml0PgojIDpMaWNlbnNlOiAgIEdOVSBHZW5lcmFsIFB1YmxpYyBMaWNlbnNlIHZlcnNpb24gMyBvciBsYXRlcgojCgpkZWYgc2ltcGxlX2FsZXJ0KCk6CiAgICB3aW5kb3cuYWxlcnQoJ0hpIHRoZXJlIScpCgpkZWYgYXR0YWNoX2hhbmRsZXIoKToKICAgIGVsID0gZG9jdW1lbnQucXVlcnlTZWxlY3RvcignYnV0dG9uJykKICAgIGVsLmFkZEV2ZW50TGlzdGVuZXIoJ2NsaWNrJywgc2ltcGxlX2FsZXJ0KQoKYXR0YWNoX2hhbmRsZXIoKQo=


Notes
-----

* A `post`__ about proposed solutions to use ES6 classes with
  `Backbone`__. See also the `bug`__ open on github.

__ http://benmccormick.org/2015/07/06/backbone-and-es6-classes-revisited/
__ http://backbonejs.org
__ https://github.com/jashkenas/backbone/issues/3560


* A `benchmark of ES6 features`__ and `discussion about it`__ on
  hacker's news.

__ https://kpdecker.github.io/six-speed/
__ https://news.ycombinator.com/item?id=11203183

* A `compatibility table of ES6 features`__ showing completeness of
  support feature by feature.

__ http://kangax.github.io/compat-table/es6/

* `A story`__ about ES6 craziest stuff... symbols

__ http://blog.keithcirkel.co.uk/metaprogramming-in-es6-symbols/


.. -*- coding: utf-8 -*-

Changes
-------

0.13 (2024-07-04)
-----------------

- allow attributes to be used as indices (i.e. ``a[b.c]``) (thanks to Todd Parsons);
- allow unaryop as indices ( i.e. negative integers ) (thanks to Todd Parsons);
- allow subscripts as indices (i.e. ``a[b[0]]``) (thanks to Todd Parsons);

0.12 (2022-07-19)
-----------------

- remove macropy
- fix evaluation from commandline
- deprecate Python 3.5 and 3.6
- tested on Python 3.10

0.11 (2020-03-30)
~~~~~~~~~~~~~~~~~

- update test infrastructure to work with latest ``pytest``;
- add support for Python 3.7 and 3.8 (thanks to Richard Höchenberger).
- do not crash when translating source with assignment typehints (
  with the help of Sirenfal)

0.10 (2018-05-12)
~~~~~~~~~~~~~~~~~

- use Macropy3 version 1.1.0b2 to avoid issues with Django

0.9 (2018-04-19)
~~~~~~~~~~~~~~~~

- add a ``--source-name`` options to be used together with
  ``--inline-map`` when using ``-s``;
- move main repository to gitlab.com/metapensiero;
- add support for default export and import;
- add documentation for the ``JS()`` marker function;
- refactor of the JS AST nodes;
- fix path splitting and joining on Windows (thanks to Roman Yakubuk);

0.8 (2017-11-16)
~~~~~~~~~~~~~~~~

- add support for ``except`` sections with more than one exception
  type and arbitrary exception variable name. Thanks to @devanlai;
- dict keys conversion fixes;
- enable ``--inline-map`` when translating a string with ``-s``;


0.7 (2017-09-08)
~~~~~~~~~~~~~~~~

- translate dicts unambiguously, using "computed member name form" for
  keys that aren't strings;
- use ``macropy`` package to deal with some of the translation
  details;
- translate ``int()`` and ``float()``;
- fix a bug that prevented BabelJS translation when keyword arguments;
  are present;

0.6 (2017-05-09)
~~~~~~~~~~~~~~~~~

- allow to define template literals and tagged templates;
- define package scopes in imports prepending names with ``__``;
- translate ``issubclass()``;
- translate lambdas as arrow functions;
- translate Python 3.6+ f-strings to ES6 template literals;
- Add translation for ``__instancecheck__`` to ``[Symbol.hasInstance]``;
- Sort imports alphabetically;

0.5 (2016-11-23)
~~~~~~~~~~~~~~~~

- translate ``tmpl("A string with js ${interpolation}")`` to ES6 template
  literals;
- preliminary support to translate names like ``d_foo`` and ``dd_bar`` to
  ``$foo`` and ``$$bar``;
- addded translation of the ``assert`` statement;
- fixed a bug in ``try...except...finally`` statement when there's no
  ``except`` section;
- added translation for ``foo is not bar`` that seems to have dedicated ast
  node;
- if the function is defined in a method but starts with ``fn_`` do not convert
  it to an arrow function. Useful to *not* maintain ``this``;
- added translation for ``callable`` and ``hasattr/getattr/setattr``;
- updated for loops to support more than one target, so now its possible to
  write loops like ``for k, v in iterable(a_map):``;
- updated documentation;
- added a new cli option ``-s`` to translate source from the command line or
  the standard input;
- fixed a pair of bugs on sourcemaps;
- added a new cli option ``--eval`` to also evaluate the produced JavaScript
  using the embedded interpreter;
- added a new cli option ``--dump-ast`` to print out the ast tree of the
  passed in string;
- added sorting to the rendered snippets/decorators/assignments so that their
  order does not change at every ricompilation;
- do not re-declare variables declare in outer scopes;

0.4 (2016-11-15)
~~~~~~~~~~~~~~~~

- updated BabelJS to version 6.18.1;
- allow to import modules with dashes inside by using dunder-inside-words
  notation (``foo__bar`` becomes ``foo-bar``);
- reuse JavaScript interpreter context to speedup translation;
- update ``in`` operator to support ES6 collections;
- added support for method and class decorators;
- added support for class properties and descriptors;
- add ``for`` loop over JS iterables;
- allow to loop over inherited properties;
- fix a bug on ``type()`` translation;
- support for ``range()`` steps;
- add support for generator functions and ``yield`` and ``yield from``
  expressions;
- optionally load babel-polyfill before evaluating code;
- fix a bug on sourcemaps having wrong references when there are documentation
  elements;
- translate ``__get__()`` and ``__set__()`` to to JS equivalents;
- implement ``dict(foo).update(bar)`` and ``dict(foo).copy``;
- documentation improvements;

0.3 (2016-04-08)
~~~~~~~~~~~~~~~~

- updates to the documentation ( with some fixes made by Hugo Herter,
  Daniel Kopitchinski and ironmaniiith)
- Translate ``str(x)`` into ``x.toString()``
- Add support for properties and classmethods
- Translate ``__len__`` and ``__str__`` methods to ``get length()``
  and ``toString()``
- Add support for slices syntax to ``.slice()``
- Fixed two bugs in sourcemaps generation
- Fixed a bug in the ``inport ... from`` translation
- Correctly include BabelJS minimized code
- Fix transpiling of stage3 features

0.2 (2016-03-29)
~~~~~~~~~~~~~~~~

- use arrow functions to retain ``this`` were possible
- translate ``async/await``
- refactoring of the ``for`` loops
- add ability to subtranslate pieces of Python code or objects. Used
  to template the creation of ``Exception`` sublasses
- add support for param defaults and keyword arguments
- updated documentation

0.1 (2016-03-21)
~~~~~~~~~~~~~~~~

- First cut of the features

            

Raw data

            {
    "_id": null,
    "home_page": "https://github.com/azazel75/metapensiero.pj",
    "name": "javascripthon",
    "maintainer": null,
    "docs_url": null,
    "requires_python": null,
    "maintainer_email": null,
    "keywords": "JavaScript EcmaScript compilation translation transpiling babel",
    "author": "Alberto Berti",
    "author_email": "alberto@arstecnica.it",
    "download_url": "https://files.pythonhosted.org/packages/50/a8/cec12d3d666d1e27e28a9d45d17ec583cfbd0f741304b759050d7b91fade/javascripthon-0.13.tar.gz",
    "platform": null,
    "description": ".. -*- coding: utf-8 -*-\n.. :Project:  metapensiero.pj -- readme\n.. :Created:  mar 01 mar 2016 15:52:36 CET\n.. :Author:   Alberto Berti <alberto@metapensiero.it>\n.. :License:  GNU General Public License version 3 or later\n..\n\n======================================================\nJavaScripthon: a Python 3 to ES6 JavaScript translator\n======================================================\n\n.. image:: https://gitlab.com/metapensiero/metapensiero.pj/badges/master/pipeline.svg\n   :target: https://gitlab.com/metapensiero/metapensiero.pj/commits/master\n   :align: left\n   :alt: tests status\n\n.. image:: https://gitlab.com/metapensiero/metapensiero.pj/badges/master/coverage.svg\n   :target: https://gitlab.com/metapensiero/metapensiero.pj/commits/master\n   :align: left\n   :alt: tests coverage\n\n.. image:: https://badges.gitter.im/javascripthon/Lobby.svg\n   :alt: Join the chat at https://gitter.im/javascripthon/Lobby\n   :target: https://gitter.im/javascripthon/Lobby?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge\n   :align: left\n\n.. figure:: http://s3.amazonaws.com/fossbytes.content/wp-content/uploads/2016/04/Javascripthon-python-js-converter.jpg\n   :alt: JavaScripthon\n   :align: left\n   :width: 750px\n\n   ..\n\n   (image courtesy of `fossBytes`__)\n\n   __ http://fossbytes.com/javascripthon-a-simple-python-to-es6-javascript-translator/\n\n\nIt is based on previous work by `Andrew Schaaf <andrew@andrewschaaf.com>`_.\n\n :author: Alberto Berti\n :contact: alberto@metapensiero.it\n :license: GNU General Public License version 3 or later\n\n.. contents:: Table of Contents\n   :backlinks: top\n\nIntroduction\n------------\n\nJavaScripthon is a small and simple Python 3.5+ translator to JavaScript which\naims to be able to translate most of the Python's core semantics without\nproviding a full python-in-js environment, as most existing translators do. It\ntries to emit code which is simple to read and check. It does so by switching\nto ES6 construct when possible/required. This allows to simplify the needs of\npolyfills for many of the expected Python behaviors.\n\nIt is designed to be the first step in a pipeline that translates your Python\ncode into something that a browser can understand. Usually it is used with\ntools like `BabelJS`__ and `Webpack`__ to prepare the final bundle that will\nbe served to the browser. The steps from the source code to the bundle are the\nfollowing:\n\n1) JavaScripthon converts your Python 3.5+ code to ES6 JavaScript modules;\n2) the BabelJS loader (configured inside Webpack or standalone) translates the\n   ES6 JavaScript to ES5 so that the browser can understand it;\n3) Webpack parses the resulting source code and packages your source code with\n   its dependencies by analyzing ``import`` statements and emits a\n   ``bundle.js`` ready to be served to the browser.\n\nAlong this process the corresponding `source maps`__ are read and integrated at\nevery step, allowing you to place breakpoints on your original Python source\nfiles when working with the developer tools of your browser.\n\nAn example of such setup is provided in the ``examples`` directory.\n\n__ http://babeljs.io/\n__ http://webpack.github.io/\n__ http://blog.teamtreehouse.com/introduction-source-maps\n\n\nIn addition to that, you can choose to do most these steps without using\nexternal JS tools. It comes with an `embedded js interpreter`__ that loads a\nstandalone version of BabelJS and converts your code to ES5 JavaScript without\nthe need to install anything else. In fact most of the the test you can find\nin ``tests/test_evaljs.py`` use the embedded interpreter to dual evaluate the\nsource code (one time in Python, one time in JavaScript) and simply check that\nthe results are the same.\n\n__ https://github.com/amol-/dukpy\n\nThanks to that, JavaScripthon can also be used as a server-side library to\ntranslate single functions or classes that you want your browser to load and\nevaluate.\n\nThe interface with the JS world is completely flat, just import the modules\nor use the expected globals (``window``, ``document``, etc...) as you\nwould do in JavaScript.\n\nBrief list of the supported Python semantics\n--------------------------------------------\n\nThe fact that JavaScripthon doesn't *reinvent the wheel* by reimplementing in\nPython many of the features available with JavaScript translators/transpilers\nallows it to be lean while implementing quite a decent set of the core Python\nsemantics. These are, briefly:\n\n* Misc\n\n  - list slices;\n  - list's ``append()``;\n  - dict's ``copy()``, ``update()``;\n  - ``len()``;\n  - ``print()``;\n  - ``str()``;\n  - ``type(instance)``;\n  - ``yield`` and ``yield from``;\n  - ``async`` and ``await``;\n  - ``import`` and ``from...import`` to use any JS module (see `import\n    statements`_);\n  - ``callable()``;\n  - ``hasattr()``, ``getattr()``, ``setattr()``;\n  - template literals with ``tmpl('a string with ${substitution}')``;\n  - simple Python 3.6+ `f-strings`_ (see `Strings`_);\n  - template literals and tagged_templates (see `Strings`_);\n  - names starting with ``d_`` and ``dd_`` will have that part replaced with\n    ``$`` and ``$$``, respectively;\n  - names ending with an underscore will have it removed. Useful for example\n    with the AVA ES6 test runner which has a check named ``is``;\n  - ``__instancecheck__`` to ``[Symbol.hasInstance]``;\n  - ``int`` to ``parseInt``;\n  - ``float`` to ``parseFloat``;\n  - dictionary keys are unambiguous when ES6 translation is\n    enabled. For example the following code gets translated correctly:\n\n    .. code:: python\n\n       a = 'foo'\n       d = {a: 1}\n       print(d[a])\n\n    prints ``1`` in both Python and JavaScript, while it prints\n    ``undefined`` when translated and evaluated in JavaScript without\n    ES6.\n\n.. _f-strings: https://docs.python.org/3.6/reference/lexical_analysis.html#f-strings\n\n* Comparisons (see section `Simple stuff`_ for the details)\n\n  - most of the basics;\n  - ``isinstance()`` and ``issubclass()``;\n  - ``element in container`` for use with lists, objects, strings and the new\n    ES6 collections like ``Map``, ``Set`` and so on;\n  - identity checks: ``foo is bar``;\n  - chained comparisons like ``x < y <= z``;\n\n* Statements (see section `Simple stuff`_ and `for statement`_ for the\n  details)\n\n  - ``if...elif...else``;\n  - ``while`` loop;\n  - ``for`` over list, over range, over plain js objects, over iterables (JS\n    iterables);\n  - ``try...except...finally`` with pythonesque behavior (see\n    `try...except...finally statement`_ section for the details);\n  - ``assert`` statement;\n\n* Functions (see `Functions`_ section)\n\n  - standard functions, generator functions, async functions;\n  - parameters defaults;\n  - keyword parameters;\n  - parameters accumulators (``*args`` and ``**kwargs``), with some\n    restrictions;\n  - functions in methods are usually converted to \"arrow functions\" (the new\n    ES6 syntax like ``(foo, bar) => foo * bar;``) because they automatically\n    keep ``this`` from the enclosing scope. Appending ``_fn`` to a function\n    declaration will force the translation to a normal function;\n\n* Classes (see `Classes`_ section)\n\n  - single inheritance;\n  - Exception classes for use with ``except`` statement;\n  - class decorators and method decorators;\n  - property descriptors;\n  - special handling of ``property`` and ``classmethod`` descriptors;\n  - async methods, generator methods;\n  - non-function body members (i.e. ``member_of_class_Foo = bar``);\n\nLicense\n-------\n\nThis package is covered by the `GNU General Public License version\n3 or later`__. The code produced by it (i.e. the transpiled\nJavaScript) is *your* code, and *you* are free to choose whatever\nlicense you like. The only ``runtime`` that exists is the file\n`snippets.py`__ from which some utility functions are picked when\nnecessary and transpiled together with your code. While it's\ndistributed with the same license as the other source code, in its\n*transpiled* form will have the license you choose.\n\nSo, to summarize, the license of the this tool is GPL, but it doesn't\nextends to the products of this tool, on which you are free to decide.\n\n__ https://www.gnu.org/licenses/gpl.html\n__ https://github.com/azazel75/metapensiero.pj/blob/master/src/metapensiero/pj/snippets.py\n\nInstallation\n------------\n\nPython 3.5 is required because Python's AST has changed between 3.4\nand 3.5 and as of now supporting multiple Python versions is not one\nof my priorities.\n\nTo install the package execute the following command::\n\n  $ pip install javascripthon\n\nor, if you want install it from sources::\n\n  $ git clone https://github.com/azazel75/metapensiero.pj\n  $ pip install -r metapensiero.pj/requirements.txt\n  $ pip install metapensiero.pj\n\nUsage\n-----\n\nTo *compile* or *transpile* a python source module, use the\ncommandline:\n\n.. code:: bash\n\n  $ python -m metapensiero.pj source.py\n\nor:\n\n.. code:: bash\n\n  $ python -m metapensiero.pj -5 source.py\n\nto transpile.\n\nA ``pj`` console script is also automatically installed:\n\n.. code:: bash\n\n\n  $ pj --help\n  usage: pj [-h] [--disable-es6] [--disable-stage3] [-5] [--transform-runtime]\n            [-o OUTPUT] [-d] [--pdb] [-s STRING] [-e]\n            [file [file ...]]\n\n  A Python 3.5+ to ES6 JavaScript compiler\n\n  positional arguments:\n    file                  Python source file(s) or directory(ies) to convert.\n                          When it is a directory it will be converted\n                          recursively\n\n  optional arguments:\n    -h, --help            show this help message and exit\n    --disable-es6         Disable ES6 features during conversion (Ignored if\n                          --es5 is specified)\n    --disable-stage3      Disable ES7 stage3 features during conversion\n    -5, --es5             Also transpile to ES5 using BabelJS.\n    --transform-runtime   Add trasform runtime as plugin during transpile\n    -o OUTPUT, --output OUTPUT\n                          Output file/directory where to save the generated code\n    -d, --debug           Enable error reporting\n    --pdb                 Enter post-mortem debug when an error occurs\n    -s STRING, --string STRING\n                          Convert a string, useful for small snippets. If the\n                          string is '-' will be read from the standard input.\n    -e, --eval            Evaluate the string supplied with the -s using the\n                          embedded interpreter and return the last result. This\n                          will convert the input string with all the extensions\n                          enabled (comparable to adding the '-5' option) and so\n                          it will take some time because of BabelJS load times.\n\nThis offers many ways to test the framework, both the string conversion and\nthe evaluation using the embedded JavaScript interpreter are very handy. For\nexample:\n\n.. code:: bash\n\n  $ pj -s '\"foo\" if True else \"bar\"'\n  (true ? \"foo\" : \"bar\");\n\nand evaluating the same statement:\n\n.. code:: bash\n\n  $ pj -s '\"foo\" if True else \"bar\"' -e\n  foo\n\nYou can even try more fancy ES6 features, like destructuring assignment:\n\n.. code:: bash\n\n   $ pj -s \"a, b, c = (2, 3, 5) \\na+b+c\" -e\n   10\n\nYou can use metapensiero.pj in python code as well.\n\n.. code:: python\n\n    from metapensiero.pj.__main__ import transform_string\n\n    transform_string(\"print()\")\n\nReporting Bugs\n--------------\n\nThe main development repository is the one on gitlab__, the one on\ngithub is just a mirror so please report issues and feature requests\nthere__.\n\n__ https://gitlab.com/metapensiero/metapensiero.pj\n__ https://gitlab.com/metapensiero/metapensiero.pj/issues\n\nConversions Rosetta Stone\n-------------------------\n\nHere is a brief list of examples of the conversions the tool applies,\njust some, but not all.\n\nSimple stuff\n~~~~~~~~~~~~\n\n.. list-table:: Most are obvious\n  :header-rows: 1\n\n  * - Python\n    - JavaScript\n\n  * - .. code:: python\n\n        x < y <= z < 5\n\n    - .. code:: javascript\n\n        ((x < y) && (y <= z) && (z < 5))\n\n  * - .. code:: python\n\n\n        def foo():\n            return [True, False, None, 1729,\n                    \"foo\", r\"foo\\bar\", {}]\n\n    - .. code:: javascript\n\n        function foo() {\n            return [true, false, null, 1729,\n                    \"foo\", \"foo\\\\bar\", {}];\n        }\n\n\n  * - .. code:: python\n\n        while len(foo) > 0:\n            print(foo.pop())\n\n    - .. code:: javascript\n\n        while ((foo.length > 0)) {\n            console.log(foo.pop());\n        }\n\n\n  * - .. code:: python\n\n        if foo > 0:\n            ....\n        elif foo < 0:\n            ....\n        else:\n            ....\n\n    - .. code:: javascript\n\n        if ((foo > 0)) {\n            ....\n        } else {\n            if ((foo < 0)) {\n                ....\n            } else {\n                ....\n            }\n        }\n\n\n  * - .. code:: python\n\n        str(x)\n\n    - .. code:: javascript\n\n        x.toString()\n\n  * - .. code:: python\n\n        yield foo\n        yield from foo\n\n    - .. code:: javascript\n\n        yield foo\n        yield* foo\n\n\nThen there are special cases. Here you can see some of these\nconversions. JavaScripthon cannot do a full trace of the sources, so\nsome shortcuts are taken about the conversion of some core, specific\nPython's semantics. For example Python's ``self`` is always converted\nto JavaScript's ``this``, no matter where it's found. Or ``len(foo)``\nis always translated to ``foo.length``. Albeit this an API specific of\njust some objects (Strings, Arrays, etc...), it is considered wide\nadopted and something the user may consider obvious.\n\nThe rules of thumb to treat things especially are:\n\n* Is it possible to think of a conversion that covers most of the use\n  cases?\n\n* Is ts possible to find a convention widely used on the Python world\n  to express this special case?\n\n.. list-table:: There are special cases\n  :header-rows: 1\n\n  * - Python\n    - JavaScript\n\n  * - .. code:: python\n\n        ==\n\n    - .. code:: javascript\n\n        ===\n\n  * - .. code:: python\n\n        !=\n\n    - .. code:: javascript\n\n        !==\n\n  * - .. code:: python\n\n        2**3\n\n    - .. code:: javascript\n\n        Math.pow(2, 3)\n\n  * - .. code:: python\n\n        'docstring'\n\n    - .. code:: javascript\n\n        /* docstring */\n\n  * - .. code:: python\n\n        self\n\n    - .. code:: javascript\n\n        this\n\n  * - .. code:: python\n\n        len(...)\n\n    - .. code:: javascript\n\n        (...).length\n\n  * - .. code:: python\n\n        print(...)\n\n    - .. code:: javascript\n\n        console.log(...)\n\n  * - .. code:: python\n\n        isinstance(x, y)\n        isinstance(x, (y, z))\n\n    - .. code:: javascript\n\n        (x instanceof y)\n        (x instanceof y || x instanceof z)\n\n  * - .. code:: python\n\n        typeof(x)\n\n    - .. code:: javascript\n\n        (typeof x)\n\n  * - .. code:: python\n\n        type(x)\n\n    - .. code:: javascript\n\n        Object.getPrototypeOf(x)\n\n  * - .. code:: python\n\n        FirstCharCapitalized(...)\n        new(any_function(...))\n\n    - .. code:: javascript\n\n        new FirstCharCapitalized(...)\n        new any_function(...)\n\n  * - .. code:: python\n\n        foo in bar\n\n    - .. code:: javascript\n\n        var _pj;\n        function _pj_snippets(container) {\n            function in_es6(left, right) {\n                if (((right instanceof Array) || ((typeof right) === \"string\"))) {\n                    return (right.indexOf(left) > (- 1));\n                } else {\n                    if (((right instanceof Map) || (right instanceof Set)\n                        || (right instanceof WeakMap)\n                        || (right instanceof WeakSet))) {\n                        return right.has(left);\n                    } else {\n                        return (left in right);\n                    }\n                }\n            }\n            container[\"in_es6\"] = in_es6;\n            return container;\n        }\n        _pj = {};\n        _pj_snippets(_pj);\n        _pj.in_es6(foo, bar);\n\n  * - .. code:: python\n\n        foo[3:]\n        foo[:3]\n\n    - .. code:: javascript\n\n        foo.slice(3);\n        foo.slice(0, 3);\n\n  * - .. code:: python\n\n        list(foo).append(bar)\n\n    - .. code:: javascript\n\n        foo.push(bar);\n\n  * - .. code:: python\n\n        dict(foo).update(bar)\n\n    - .. code:: javascript\n\n        Object.assign(foo, bar);\n\n  * - .. code:: python\n\n        dict(foo).copy()\n\n    - .. code:: javascript\n\n        Object.assign({}, foo);\n\n\n``for`` statement\n~~~~~~~~~~~~~~~~~\n\nThe ``for`` statement by default is translated as if the object of the\ncycle is a list but has two special cases:\n\n\n.. list-table:: ``for`` loops\n  :header-rows: 1\n\n  * - Python\n    - JavaScript\n    - notes\n\n  * - .. code:: python\n\n        for el in dict(a_dict):\n            print(el)\n\n    - .. code:: javascript\n\n        var _pj_a = a_dict;\n        for (var el in _pj_a) {\n            if (_pj_a.hasOwnProperty(el)) {\n                console.log(el);\n            }\n        }\n\n    - With this kind of loop if you use ``dict(a_dict, True)`` the check on\n      ``hasOwnProperty()`` will not be added, so the loop will include\n      *inherited* (and *enumerable*) properties.\n\n  * - .. code:: python\n\n        for el in an_array:\n            print(el)\n\n    - .. code:: javascript\n\n        for (var el, _pj_c = 0, _pj_a = an_array, _pj_b = _pj_a.length;\n              (_pj_c < _pj_b); _pj_c += 1) {\n            el = _pj_a[_pj_c];\n            console.log(el);\n        }\n\n    -\n\n  * - .. code:: python\n\n        for i in range(5):\n            print(i)\n\n    - .. code:: javascript\n\n        for (var i = 0, _pj_a = 5; (i < _pj_a); i += 1) {\n            console.log(i);\n        }\n\n    -\n\n  * - .. code:: python\n\n        for el in iterable(a_set):\n            print(el)\n\n    - .. code:: javascript\n\n        var _pj_a = a_set;\n        for (var el of  _pj_a) {\n            console.log(el);\n        }\n\n    - This will loop over all the iterables, like instances of ``Array``,\n      ``Map``, ``Set``, etc. **but not over normal objects**.\n\nFunctions\n~~~~~~~~~\n\nFunctions are very well supported. This should be obvious, you can say. Really\nit is not so simple, if we mean functions in their broader meaning, including\nthe  *async functions* and *generator functions*.\n\n.. list-table:: The various types of functions at play\n  :header-rows: 1\n\n  * - Python\n    - JavaScript\n    - notes\n\n  * - .. code:: python\n\n        def foo(a, b, c):\n            pass\n\n    - .. code:: javascript\n\n        function foo(a, b, c) {\n        }\n\n    - Normal functions\n\n  * - .. code:: python\n\n        def foo(a, b, c):\n            for i in range(a, b, c):\n                yield i\n\n        for i in iterable(foo(0, 5, 2)):\n            print(i)\n\n    - .. code:: javascript\n\n        function* foo(a, b, c) {\n            for ... { // loop control omitted for brevity\n                yield i;\n            }\n        }\n\n        for (var i of foo(0, 5, 2)) {\n            console.log(i);\n        }\n\n    - Generator functions. They return an iterable and to correctly loop over\n      it you should use the ``iterable(...)`` call, so that the Python's\n      ``for...in`` will be converted into a ``for...of``\n\n  * - .. code:: python\n\n        async def foo(a, b, c):\n            await some_promise_based_async\n\n\n    - .. code:: javascript\n\n        async function foo(a, b, c) {\n            await some_promised_base_async;\n        }\n\n    - Async functions. They make use of the new ``Promise`` class, which is\n      also available.\n\n\nFunction's args and call parameters\n+++++++++++++++++++++++++++++++++++\n\nParmeters defaults and keyword parameters are supported and so is ``*foo``\naccumulator, which is translated into the ES6 rest expression (``...foo``).\n\nThe only caveat is that JS support for keyword args sucks, so you will have to\n**remember to fill in all the arguments before specifying keywords**.\n\nOn function definitions, ``**kwargs`` is supported if it's alone, i.e. without\neither keyword arguments or ``*args``.\n\n.. list-table:: function's args and call parameters\n  :header-rows: 1\n\n  * - Python\n    - JavaScript\n\n  * - .. code:: python\n\n        def foo(a=2, b=3, *args):\n            pass\n\n    - .. code:: javascript\n\n        function foo(a = 2, b = 3, ...args) {\n        }\n\n  * - .. code:: python\n\n        def bar(c, d, *, zoo=2):\n            pass\n\n    - .. code:: javascript\n\n        function bar(c, d, {zoo = 2}={}) {\n        }\n\n  * - .. code:: python\n\n        foo(5, *a_list)\n\n    - .. code:: javascript\n\n        foo(5, ...a_list);\n\n  * - .. code:: python\n\n        bar('a', 'b', zoo=5, another='c')\n\n    - .. code:: javascript\n\n        bar(\"a\", \"b\", {zoo: 5, another: \"c\"});\n\n  * - .. code:: python\n\n        def zoo(e, **kwargs):\n            print(kwargs['bar'])\n\n    - .. code:: javascript\n\n        function zoo(e, kwargs = {}) {\n            console.log(kwargs['bar'])\n        }\n\n  * - .. code:: python\n\n        zoo(4, bar=6)\n\n    - .. code:: javascript\n\n        zoo(4, {bar: 6})\n\nClasses\n~~~~~~~\n\nClasses are translated to ES6 classes as much as they can support. This means:\n\n* no direct support multi-class inheritance, you have to come up with your own\n  solution for now. Many established frameworks support this in a way or\n  another so just use those facilities for now. I've read of some attempts,\n  see for example the suggestion on `Mozilla developer`__ or the other about\n  `simple mixins`__ on ``Exploring ES6``.\n\n* external implementation for class-level non assignment members. Assignment\n  members are those on the body of a class which are defined with: ``a_label =\n  an_expression`` like:\n\n  .. code:: python\n\n    class Foo:\n\n        bar = 'zoo' # or any kind of expression\n\n  These members are removed from the translated body and submitted to a\n  snippet of code that will run after class creation in JS land. This serves\n  two purposes: if the value is *simple*, i.e. it isn't an instance of\n  ``Object``, it will be setup as a *data descriptor*, and it will work mostly\n  like you are used to in Python. The most noticeable caveat is that it will\n  not be accessible through the class as it is in Python, you will have to\n  access the class' *prototype*, so in the case above i mean\n  ``Foo.prototype.bar``.\n\n  The other purpose is to check for *accessor descriptors*. If the value on\n  the right side of the assignment implements a ``get`` function, it will be\n  installed as a property as-is, and its *get* and *set* members will be used\n  to manage the value with the ``bar`` name.\n\n* external implementation for method decorators whose name is different from\n  ``property`` or ``classmethod`` (more on these later on), because these are\n  already supported by the ES6 class notation.\n\n* external implementation for class decorators. One caveat here is that the\n  return value of the decorator has always to be a function with a prototype:\n  unfortunately a ``new`` statement seems not to be *delegable* in any way. So\n  for example a class decorator implemented like the following:\n\n  .. code:: python\n\n    def test_class_deco():\n\n        counter = 0\n\n        def deco(cls):\n            def wrapper(self, *args):\n                counter += 1 # side effect\n                return cls(*args)\n            return wrapper\n\n        @deco\n        class Foo:\n            pass\n\n  will never work. This will work instead:\n\n  .. code:: python\n\n    def deco(cls):\n        def wrapper(self, *args):\n            counter += 1 # side effect\n            return cls.prototype.constructor.call(self, *args)\n        wrapper.prototype = cls.prototype\n        return wrapper\n\n  So either return the original class or setup the wrapper appropriately.\n\n\n__ https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes#Mix-ins\n__ http://exploringjs.com/es6/ch_classes.html#_simple-mixins\n\n\nMethods can be functions or async-functions although the latters aren't\nofficially supported yet by the JavaScript specification. You can disable them\nadding a ``--disable-stage3`` to the command line utility.\n\nPython`s ``super()`` calls are converted accordingly to the type of\ntheir surrounding method: ``super().__init__(foo)`` becomes\n``super(foo)`` in constructors.\n\nFunctions inside methods are translated to arrow functions so that\nthey keep the ``this`` of the surrounding method.\n\n``@property`` and ``@a_property.setter`` are translated to ES6 properties.\n\nMethods decorated with ``@classmethod`` are translated to ``static`` methods.\n\nSpecial methods ``__str__`` and ``__len__`` are translated to\n``toString()`` method and ``get length()`` property, respectively.\n\nArrow method expression to retain the ``this`` at method level aren't\nimplemented yet.\n\n\n.. list-table:: Classes\n  :header-rows: 1\n\n  * - Python\n    - JavaScript\n\n  * - .. code:: python\n\n        class Foo(bar):\n            def __init__(self, zoo):\n                super().__init__(zoo)\n\n\n            def meth(self, zoo):\n                super().meth(zoo)\n                def cool(a, b, c):\n                    print(self.zoo)\n\n\n            async def something(self, a_promise):\n                result = await a_promise\n\n            def generator_method(self):\n                yield something\n\n            @property\n            def foo(self):\n                return self._foo\n\n\n            @foo.setter\n            def foo(self, value):\n                self._foo = value\n\n\n            @classmethod\n            def bar(self, val):\n                do_something()\n\n\n            def __len__(self):\n                return 1\n\n\n            def __str__(self):\n                return 'Foo instance'\n\n    - .. code:: javascript\n\n        class Foo extends bar {\n            constructor(zoo) {\n                super(zoo);\n            }\n\n            meth(zoo) {\n                super.meth(zoo);\n                var cool;\n                cool = (a, b, c) => {\n                    console.log(this.zoo);\n                };\n            }\n\n            async something(a_promise) {\n                var result;\n                result = await a_promise;\n            }\n\n            * generator_method() {\n                yield something;\n            }\n\n            get foo() {\n                return this._foo;\n            }\n\n            set foo(value) {\n                self._foo = value;\n            }\n\n            static bar(val) {\n                do_something()\n            }\n\n            get length() {\n                return 1;\n            }\n\n            toString() {\n                return \"Foo instance\";\n            }\n        }\n\nOnly direct descendants of ``Exception`` are treated especially, but\njust for them to be meaningful in JS land and to be detectable with\n``instanceof`` in catch statements.\n\n\n.. list-table:: Exceptions\n  :header-rows: 1\n\n  * - Python\n    - JavaScript\n\n  * - .. code:: python\n\n        class MyError(Exception):\n            pass\n\n        raise MyError(\"An error occurred\")\n\n    - .. code:: javascript\n\n        function MyError(message) {\n            this.name = \"MyError\";\n            this.message = (message || \"Custom error MyError\");\n            if (((typeof Error.captureStackTrace) === \"function\")) {\n                Error.captureStackTrace(this, this.constructor);\n            } else {\n                this.stack = new Error(message).stack;\n            }\n        }\n        MyError.prototype = Object.create(Error.prototype);\n        MyError.prototype.constructor = MyError;\n        throw new MyError(\"An error occurred\");\n\n\n``try...except...finally`` statement\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\nThe conversion of this statement is mostly obvious with the only\nexception of the ``except`` part: it translates to a ``catch`` part\ncontaining one ``if`` statement for each non catchall ``except``. If a\ncatchall ``except`` isn't present, the error will be re-thrown, to mimic\nPython's behavior.\n\n.. list-table:: ``try...catch...finally`` statement\n  :header-rows: 1\n\n  * - Python\n    - JavaScript\n\n  * - .. code:: python\n\n        try:\n            foo.bar()\n        except MyError:\n            recover()\n        except MyOtherError:\n            recover_bad()\n        finally:\n            foo.on_end()\n\n    - .. code:: javascript\n\n        try {\n            foo.bar();\n        } catch(e) {\n            if ((e instanceof MyError)) {\n                recover();\n            } else {\n                if ((e instanceof MyOtherError)) {\n                    recover_bad()\n                } else {\n                    throw e;\n                }\n            }\n        } finally {\n            foo.on_end();\n        }\n\n\n``import`` statements\n~~~~~~~~~~~~~~~~~~~~~\n\n``import`` and ``from ... import`` statements are converted to ES6\nimports, and the declaration of an ``__all__`` member on the module\ntop level is translated to ES6 named exports.\n\n.. list-table:: import and exports\n  :header-rows: 1\n\n  * - Python\n    - JavaScript\n\n  * - .. code:: python\n\n        import foo, bar\n        import foo.bar as b\n        from foo.bar import hello as h, bye as bb\n        from ..foo.zoo import bar\n        from . import foo\n        from .foo import bar\n\n        from foo__bar import zoo\n\n        from __foo.zoo import bar\n\n        from foo import __default__ as bar\n\n        from __globals__ import test_name\n\n        # this should not trigger variable definition\n        test_name = 2\n\n        # this instead should do it\n        test_foo = True\n\n        __all__ = ['test_name', 'test_foo']\n        __default__ = 'test_name'\n\n    - .. code:: javascript\n\n        var test_foo;\n\n        import * as foo from 'foo';\n        import * as bar from 'bar';\n        import * as b from 'foo/bar';\n        import {hello as h, bye as bb} from 'foo/bar';\n        import {bar} from '../foo/zoo';\n        import * as foo from './foo';\n        import {bar} from './foo';\n\n        import {zoo} from 'foo-bar';\n\n        import {bar} from '@foo/zoo';\n\n        import bar from 'foo';\n\n        test_name = 2;\n        test_foo = true;\n\n        export {test_name, test_foo};\n        export default test_name;\n\nAbout JS **default** ``export`` and ``import``\n++++++++++++++++++++++++++++++++++++++++++++++\n\nIf you want to export something as *default export* in your modules,\ndeclare a ``__default__`` member and assign to it the string of the\nsymbol you want to export. To clarify:\n\n.. code:: python\n\n  foo = 42\n  bar = \"hello\"\n\n  __all__ = ['foo', 'bar']  # foo and bar will be exported as named exports\n  __default__ = 'bar'  # bar will also be exported as the *default*\n\nThis becomes:\n\n.. code:: javascript\n\n  var bar, foo;\n\n  foo = 42;\n  bar = \"hello\";\n\n  export {foo, bar};\n  export default bar;\n\nFor what concerns the ``import``, you can import the default export of\na module using the ``default`` name, as defined by the ES6\nspec. However, as there were some issues reported to me with bundlers\nnot supporting the named import of the default export, a special\n``import`` statement using ``__default__ as name`` has been added that\ndirectly translates to the more common form of ES6 default import. So:\n\n.. code:: python\n\n  from foo import default as bar\n  from foo import __default__ as zoo\n\nTranslates to:\n\n.. code:: javascript\n\n  import {default as bar} from 'foo';\n  import zoo from 'foo';\n\nThe two imports should work the same, see `exploring js section`__ and\nthe linked spec. But if you encounter problems with the former use\nthe latter instead. Keep in mind that you cannot mix the\n``__default__`` import with others (i.e. it needs to be on a line of\nits own) and that you always need to specify an ``... as name ...`` part.\n\n__ http://exploringjs.com/es6/ch_modules.html#sec_importing-exporting-details\n\nStrings\n-------\n\nJavascripthon supports converting Python 3.6+ `f-strings`_ to ES6\n`template literals`_. The expression in the braces gets converted, but\nneither `conversion`__ nor `format_spec`__ are supported: ``f\"Value of\n{a}\"`` becomes ```Value of ${a}``` and ``f\"Value of {self.foo}\"``\nbecomes ```Value of ${this.foo}```.\n\n.. _template literals: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals\n__ https://docs.python.org/3.6/reference/lexical_analysis.html#grammar-token-conversion\n__ https://docs.python.org/3.6/reference/lexical_analysis.html#grammar-token-format_spec\n\nYou can also write *raw* template literals by using the function\n``tmpl()`` it does only a conversion of the string markers, from those\nused in Python's literal string notation to template literal notation.\n\nThere is also the way to express *tagged templates*, template literals\nthat are parsed using a provided function. This is done by using the\nfunction ``__``. So for example:\n\n.. code:: python\n\n  __('A template ${string} with foo', bar)\n\ngets translated to:\n\n.. code:: javascript\n\n  bar`A template ${string} with foo`\n\n``bar`` will be executed with the value of ``${string}`` as a\nparameter, see the link for `template literals`_ for help.\n\nVerbatim JS\n-----------\n\nYou can intermix Python and JS by using the\n``JS('Your-JS-code-here')`` marker function. It will not be touched by\nthe ES6 transcoder but if you choose to also transpile it to ES5, il\nwill be considered by Babel.\n\n\nExamples\n--------\n\nExecute ``make`` inside the ``examples`` directory.\n\nTesting\n-------\n\nTo run the tests you should run the following at the package root::\n\n  python setup.py test\n\nHow to contribute\n-----------------\n\nSo you like this project and want to contribute? Good!\n\nThese are the terse guidelines::\n\n  There are some TODO points in the readme, or even the issue #6 is\n  quite simple to fix. Feel free to pick what you like.\n\n  The guidelines are to follow PEP8 for coding where possible, so use\n  CamelCase for classes and snake_case for variables, functions and\n  members, and UPPERCASE for constants.\n\n  An exception to this rules are the function names inside\n  ``metapensiero.pj.transformations`` subpackage. Those are matched\n  against names of the AST objects coming from the ``ast`` module in\n  standard lib, so they have to to match even in case.\n\n  Try to keep lines lengths under 79 chars, more or less ;-)\n\n  The workflow is to fork the project, do your stuff, maybe add a test\n  for it and then submit a pull request.\n\n  Have fun\n\nContributing\n------------\n\nAny contribution is welcome, drop me a line or file a pull request.\n\nExternal contributions\n----------------------\n\n* `BrainBacon`__ has made a `JavaScripthon loader`__ for WebPack;\n\n* `icarito`_ has contributed support for JavaScripthon to the\n  `python-webpack-loader`__ for WebPack (Every valid JS package has at\n  least two implementations! ROTFL);\n\n* `icarito`_ has also `integrated JavaScripthon with Nuxt.js and\n  Vue.js`__;\n\n* `chfw`__ has integrated `JavaScripthon into pyecharts`__ to allow\n  Python function translation.\n\n.. _icarito: https://github.com/icarito\n__ https://github.com/BrainBacon\n__ https://github.com/Beg-in/javascripthon-loader\n__ https://github.com/martim00/python-webpack-loader\n__ https://nuxt-python.surge.sh/\n__ https://github.com/chfw\n__ https://github.com/pyecharts/pyecharts\n\nTodo\n----\n\nThis is a brief list of what needs to be done:\n\n* refactor the comprehensions conversion to use the snippets facility;\n* refactor snippets rendering to write them as a module and import\n  them in the module when tree conversion is enabled;\n* convert ``dict()`` calls to ES6 ``Map`` object creation;\n* convert *set* literals to ES6 ``Set`` objects. Also, update\n  \"foo in bar\" to use bar.has(foo) for sets;\n\nDone\n----\n\nStuff that was previously in the todo:\n\n* translate *import* statements to ES6;\n* translate ``__all__`` definition to ES6 module exports;\n* write a command line interface to expose the api;\n* make try...except work again and implement try...finally;\n* convert *async* and *await* to the same proposed features for js\n  (see BabelJS documentation);\n* convert argument defaults on functions to ES6;\n* convert call keyword arguments;\n* convert `*iterable` syntax to ES6 destructuring;\n* use arrow functions for functions created in functions;\n* properties to ES6 properties (getter and setter);\n* take advantage of new duckpy features to use a JS execution context\n  that lasts multiple calls. This way the BabelJS bootstrap affects\n  only the initial execution;\n* class and method decorators;\n* implement *yield*, *yield from* and generator functions;\n* update \"foo in bar\" to use bar.has(foo) for maps;\n\n\nExternal documentation\n----------------------\n\nA good documentation and explanation of ES6 features can be found on\nthe book `Exploring ES6`__ by Axel Rauschmayer (donate if you can).\n\n__ http://exploringjs.com/es6/\n\nAn `extensive documentation`__ about Python's AST objects, very handy.\n\n__ https://greentreesnakes.readthedocs.org/en/latest/\n\nTools\n-----\n\nHave a look at `ECMAScript 6 Tools`__ by Addy Osmani.\n\n__ https://github.com/addyosmani/es6-tools\n\nTo debug *source maps* have a look at `source-map-visualization`__ and\nits `package`__ on npm.\n\n__ https://sokra.github.io/source-map-visualization/\n__ https://www.npmjs.com/package/source-map-visualize\n\nStill i found these links to be helpful:\n\n* `BASE64 VLQ CODEC (COder/DECoder)`__\n* `Testing Source Maps`__\n\n__ http://murzwin.com/base64vlq.html\n__ http://fitzgeraldnick.com/2013/08/02/testing-source-maps.html\n\nHere is an `example`__ of the latter tool showing code generated by\nJavaScripthon, have fun!\n\n__ https://sokra.github.io/source-map-visualization/#base64,ZnVuY3Rpb24gc2ltcGxlX2FsZXJ0KCkgewogICAgd2luZG93LmFsZXJ0KCJIaSB0aGVyZSEiKTsKfQpmdW5jdGlvbiBhdHRhY2hfaGFuZGxlcigpIHsKICAgIHZhciBlbDsKICAgIGVsID0gZG9jdW1lbnQucXVlcnlTZWxlY3RvcigiYnV0dG9uIik7CiAgICBlbC5hZGRFdmVudExpc3RlbmVyKCJjbGljayIsIHNpbXBsZV9hbGVydCk7Cn0KYXR0YWNoX2hhbmRsZXIoKTsKCi8vIyBzb3VyY2VNYXBwaW5nVVJMPWh0bWxfdGVzdC5qcy5tYXAK,eyJtYXBwaW5ncyI6IkFBT0E7SUFDSUEsTUFBQUMsTUFBQSxDQUFhLFdBQWI7QUFESjtBQUdBOztJQUNJQyxLQUFLQyxRQUFBQyxjQUFBLENBQXVCLFFBQXZCO0lBQ0xGLEVBQUFHLGlCQUFBLENBQW9CLE9BQXBCLEVBQTZCQyxZQUE3QjtBQUZKO0FBSUFDLGNBQUEiLCJzb3VyY2VzIjpbImh0bWxfdGVzdC5weSJdLCJ2ZXJzaW9uIjozLCJuYW1lcyI6WyJ3aW5kb3ciLCJ3aW5kb3cuYWxlcnQiLCJlbCIsImRvY3VtZW50IiwiZG9jdW1lbnQucXVlcnlTZWxlY3RvciIsImVsLmFkZEV2ZW50TGlzdGVuZXIiLCJzaW1wbGVfYWxlcnQiLCJhdHRhY2hfaGFuZGxlciJdLCJzb3VyY2VzQ29udGVudCI6WyIjIC0qLSBjb2Rpbmc6IHV0Zi04IC0qLVxuIyA6UHJvamVjdDogIHBqIC0tIHRlc3QgZm9yIGh0bWxcbiMgOkNyZWF0ZWQ6ICAgIG1hciAwMSBtYXIgMjAxNiAyMzo0ODo1MiBDRVRcbiMgOkF1dGhvcjogICAgQWxiZXJ0byBCZXJ0aSA8YWxiZXJ0b0BtZXRhcGVuc2llcm8uaXQ+XG4jIDpMaWNlbnNlOiAgIEdOVSBHZW5lcmFsIFB1YmxpYyBMaWNlbnNlIHZlcnNpb24gMyBvciBsYXRlclxuI1xuXG5kZWYgc2ltcGxlX2FsZXJ0KCk6XG4gICAgd2luZG93LmFsZXJ0KCdIaSB0aGVyZSEnKVxuXG5kZWYgYXR0YWNoX2hhbmRsZXIoKTpcbiAgICBlbCA9IGRvY3VtZW50LnF1ZXJ5U2VsZWN0b3IoJ2J1dHRvbicpXG4gICAgZWwuYWRkRXZlbnRMaXN0ZW5lcignY2xpY2snLCBzaW1wbGVfYWxlcnQpXG5cbmF0dGFjaF9oYW5kbGVyKClcbiJdfQ==,IyAtKi0gY29kaW5nOiB1dGYtOCAtKi0KIyA6UHJvamVjdDogIHBqIC0tIHRlc3QgZm9yIGh0bWwKIyA6Q3JlYXRlZDogICAgbWFyIDAxIG1hciAyMDE2IDIzOjQ4OjUyIENFVAojIDpBdXRob3I6ICAgIEFsYmVydG8gQmVydGkgPGFsYmVydG9AbWV0YXBlbnNpZXJvLml0PgojIDpMaWNlbnNlOiAgIEdOVSBHZW5lcmFsIFB1YmxpYyBMaWNlbnNlIHZlcnNpb24gMyBvciBsYXRlcgojCgpkZWYgc2ltcGxlX2FsZXJ0KCk6CiAgICB3aW5kb3cuYWxlcnQoJ0hpIHRoZXJlIScpCgpkZWYgYXR0YWNoX2hhbmRsZXIoKToKICAgIGVsID0gZG9jdW1lbnQucXVlcnlTZWxlY3RvcignYnV0dG9uJykKICAgIGVsLmFkZEV2ZW50TGlzdGVuZXIoJ2NsaWNrJywgc2ltcGxlX2FsZXJ0KQoKYXR0YWNoX2hhbmRsZXIoKQo=\n\n\nNotes\n-----\n\n* A `post`__ about proposed solutions to use ES6 classes with\n  `Backbone`__. See also the `bug`__ open on github.\n\n__ http://benmccormick.org/2015/07/06/backbone-and-es6-classes-revisited/\n__ http://backbonejs.org\n__ https://github.com/jashkenas/backbone/issues/3560\n\n\n* A `benchmark of ES6 features`__ and `discussion about it`__ on\n  hacker's news.\n\n__ https://kpdecker.github.io/six-speed/\n__ https://news.ycombinator.com/item?id=11203183\n\n* A `compatibility table of ES6 features`__ showing completeness of\n  support feature by feature.\n\n__ http://kangax.github.io/compat-table/es6/\n\n* `A story`__ about ES6 craziest stuff... symbols\n\n__ http://blog.keithcirkel.co.uk/metaprogramming-in-es6-symbols/\n\n\n.. -*- coding: utf-8 -*-\n\nChanges\n-------\n\n0.13 (2024-07-04)\n-----------------\n\n- allow attributes to be used as indices (i.e. ``a[b.c]``) (thanks to Todd Parsons);\n- allow unaryop as indices ( i.e. negative integers ) (thanks to Todd Parsons);\n- allow subscripts as indices (i.e. ``a[b[0]]``) (thanks to Todd Parsons);\n\n0.12 (2022-07-19)\n-----------------\n\n- remove macropy\n- fix evaluation from commandline\n- deprecate Python 3.5 and 3.6\n- tested on Python 3.10\n\n0.11 (2020-03-30)\n~~~~~~~~~~~~~~~~~\n\n- update test infrastructure to work with latest ``pytest``;\n- add support for Python 3.7 and 3.8 (thanks to Richard H\u00f6chenberger).\n- do not crash when translating source with assignment typehints (\n  with the help of Sirenfal)\n\n0.10 (2018-05-12)\n~~~~~~~~~~~~~~~~~\n\n- use Macropy3 version 1.1.0b2 to avoid issues with Django\n\n0.9 (2018-04-19)\n~~~~~~~~~~~~~~~~\n\n- add a ``--source-name`` options to be used together with\n  ``--inline-map`` when using ``-s``;\n- move main repository to gitlab.com/metapensiero;\n- add support for default export and import;\n- add documentation for the ``JS()`` marker function;\n- refactor of the JS AST nodes;\n- fix path splitting and joining on Windows (thanks to Roman Yakubuk);\n\n0.8 (2017-11-16)\n~~~~~~~~~~~~~~~~\n\n- add support for ``except`` sections with more than one exception\n  type and arbitrary exception variable name. Thanks to @devanlai;\n- dict keys conversion fixes;\n- enable ``--inline-map`` when translating a string with ``-s``;\n\n\n0.7 (2017-09-08)\n~~~~~~~~~~~~~~~~\n\n- translate dicts unambiguously, using \"computed member name form\" for\n  keys that aren't strings;\n- use ``macropy`` package to deal with some of the translation\n  details;\n- translate ``int()`` and ``float()``;\n- fix a bug that prevented BabelJS translation when keyword arguments;\n  are present;\n\n0.6 (2017-05-09)\n~~~~~~~~~~~~~~~~~\n\n- allow to define template literals and tagged templates;\n- define package scopes in imports prepending names with ``__``;\n- translate ``issubclass()``;\n- translate lambdas as arrow functions;\n- translate Python 3.6+ f-strings to ES6 template literals;\n- Add translation for ``__instancecheck__`` to ``[Symbol.hasInstance]``;\n- Sort imports alphabetically;\n\n0.5 (2016-11-23)\n~~~~~~~~~~~~~~~~\n\n- translate ``tmpl(\"A string with js ${interpolation}\")`` to ES6 template\n  literals;\n- preliminary support to translate names like ``d_foo`` and ``dd_bar`` to\n  ``$foo`` and ``$$bar``;\n- addded translation of the ``assert`` statement;\n- fixed a bug in ``try...except...finally`` statement when there's no\n  ``except`` section;\n- added translation for ``foo is not bar`` that seems to have dedicated ast\n  node;\n- if the function is defined in a method but starts with ``fn_`` do not convert\n  it to an arrow function. Useful to *not* maintain ``this``;\n- added translation for ``callable`` and ``hasattr/getattr/setattr``;\n- updated for loops to support more than one target, so now its possible to\n  write loops like ``for k, v in iterable(a_map):``;\n- updated documentation;\n- added a new cli option ``-s`` to translate source from the command line or\n  the standard input;\n- fixed a pair of bugs on sourcemaps;\n- added a new cli option ``--eval`` to also evaluate the produced JavaScript\n  using the embedded interpreter;\n- added a new cli option ``--dump-ast`` to print out the ast tree of the\n  passed in string;\n- added sorting to the rendered snippets/decorators/assignments so that their\n  order does not change at every ricompilation;\n- do not re-declare variables declare in outer scopes;\n\n0.4 (2016-11-15)\n~~~~~~~~~~~~~~~~\n\n- updated BabelJS to version 6.18.1;\n- allow to import modules with dashes inside by using dunder-inside-words\n  notation (``foo__bar`` becomes ``foo-bar``);\n- reuse JavaScript interpreter context to speedup translation;\n- update ``in`` operator to support ES6 collections;\n- added support for method and class decorators;\n- added support for class properties and descriptors;\n- add ``for`` loop over JS iterables;\n- allow to loop over inherited properties;\n- fix a bug on ``type()`` translation;\n- support for ``range()`` steps;\n- add support for generator functions and ``yield`` and ``yield from``\n  expressions;\n- optionally load babel-polyfill before evaluating code;\n- fix a bug on sourcemaps having wrong references when there are documentation\n  elements;\n- translate ``__get__()`` and ``__set__()`` to to JS equivalents;\n- implement ``dict(foo).update(bar)`` and ``dict(foo).copy``;\n- documentation improvements;\n\n0.3 (2016-04-08)\n~~~~~~~~~~~~~~~~\n\n- updates to the documentation ( with some fixes made by Hugo Herter,\n  Daniel Kopitchinski and ironmaniiith)\n- Translate ``str(x)`` into ``x.toString()``\n- Add support for properties and classmethods\n- Translate ``__len__`` and ``__str__`` methods to ``get length()``\n  and ``toString()``\n- Add support for slices syntax to ``.slice()``\n- Fixed two bugs in sourcemaps generation\n- Fixed a bug in the ``inport ... from`` translation\n- Correctly include BabelJS minimized code\n- Fix transpiling of stage3 features\n\n0.2 (2016-03-29)\n~~~~~~~~~~~~~~~~\n\n- use arrow functions to retain ``this`` were possible\n- translate ``async/await``\n- refactoring of the ``for`` loops\n- add ability to subtranslate pieces of Python code or objects. Used\n  to template the creation of ``Exception`` sublasses\n- add support for param defaults and keyword arguments\n- updated documentation\n\n0.1 (2016-03-21)\n~~~~~~~~~~~~~~~~\n\n- First cut of the features\n",
    "bugtrack_url": null,
    "license": "GPLv3+",
    "summary": "Javascript for refined palates: a Python 3 to ES6 Javascript translator",
    "version": "0.13",
    "project_urls": {
        "Homepage": "https://github.com/azazel75/metapensiero.pj"
    },
    "split_keywords": [
        "javascript",
        "ecmascript",
        "compilation",
        "translation",
        "transpiling",
        "babel"
    ],
    "urls": [
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "9013915796fd1e6abab2389f287405f281f069182ac259e588268cc7f936f046",
                "md5": "b18d291661acbe4025ddb78289bb4e99",
                "sha256": "5a9bda2c4f2b8e6f569eb228a0b97a111d413e2b5644cd77fcc0f52d34a0c3ad"
            },
            "downloads": -1,
            "filename": "javascripthon-0.13-py3-none-any.whl",
            "has_sig": false,
            "md5_digest": "b18d291661acbe4025ddb78289bb4e99",
            "packagetype": "bdist_wheel",
            "python_version": "py3",
            "requires_python": null,
            "size": 526798,
            "upload_time": "2024-07-04T15:33:39",
            "upload_time_iso_8601": "2024-07-04T15:33:39.993234Z",
            "url": "https://files.pythonhosted.org/packages/90/13/915796fd1e6abab2389f287405f281f069182ac259e588268cc7f936f046/javascripthon-0.13-py3-none-any.whl",
            "yanked": false,
            "yanked_reason": null
        },
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "50a8cec12d3d666d1e27e28a9d45d17ec583cfbd0f741304b759050d7b91fade",
                "md5": "e79649235a8574fca27f42aafa23f142",
                "sha256": "aef945c3c544f3c527b6497a01a3e057d2049b9a2f660f99ad0cf1da7995bfdb"
            },
            "downloads": -1,
            "filename": "javascripthon-0.13.tar.gz",
            "has_sig": false,
            "md5_digest": "e79649235a8574fca27f42aafa23f142",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": null,
            "size": 544270,
            "upload_time": "2024-07-04T15:33:43",
            "upload_time_iso_8601": "2024-07-04T15:33:43.295260Z",
            "url": "https://files.pythonhosted.org/packages/50/a8/cec12d3d666d1e27e28a9d45d17ec583cfbd0f741304b759050d7b91fade/javascripthon-0.13.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2024-07-04 15:33:43",
    "github": true,
    "gitlab": false,
    "bitbucket": false,
    "codeberg": false,
    "github_user": "azazel75",
    "github_project": "metapensiero.pj",
    "travis_ci": true,
    "coveralls": false,
    "github_actions": false,
    "requirements": [],
    "lcname": "javascripthon"
}
        
Elapsed time: 0.33490s