Upgrade to Pro — share decks privately, control downloads, hide ads and more …

altJSとしてのPython / PyCon JP 2018

7pairs
September 18, 2018

altJSとしてのPython / PyCon JP 2018

7pairs

September 18, 2018
Tweet

More Decks by 7pairs

Other Decks in Programming

Transcript

  1. Python as altJS
    - Let's write the front-end in Python.
    2018-09-18 (PyCon JP 2018)
    Junya HASEBA

    View Slide

  2. Contents
    1. Introduction
    2. About altJS
    3. About Transcrypt
    4. Transcrypt with JavaScript package
    5. Summary

    View Slide

  3. 1. Introduction

    View Slide

  4. Who am I ?
    • Junya HASEBA (@7pairs)
    • Android / Web engineer
    • Java / Kotlin
    • C#
    • JavaScript

    View Slide

  5. Advertisement
    - Sorry, this slide is written in Japanese.
    • ٕज़ॻయ5 (10/8 ஑ାαϯγϟΠϯγςΟ) ʹαʔΫϧࢀՃ (͔09)
    • ʰ΄΅Python͚ͩͰαʔόʔϨεΞϓϦΛͭ͘Ζ͏ʱΛ൦෍
    • Chalice (όοΫΤϯυ)
    • Transcrypt (ϑϩϯτΤϯυ)
    • pytest (Ϣχοτςετ, APIςετ)
    • Selene (UIςετ)

    View Slide

  6. 2. About altJS

    View Slide

  7. What’s altJS ?
    • Programming languages that transcompiles to
    JavaScript.
    • TypeScript
    • CoffeeScript
    • Hexe
    • etc...

    View Slide

  8. Other language -> JavaScript
    • Kotlin/JS (Kotlin)
    • ClojureScript (Clojure)
    • GopherJS (Go)
    • ShiftJS (Swift)
    • etc...

    View Slide

  9. Python -> JavaScript…!

    View Slide

  10. Python -> JavaScript
    Batavia, Brython, Bulbul, Empythoned,
    FiddleSalad, Flexx, JavaScripthon, Jiphy, PJs,
    py2js, PyCow, Pyjaco, Pyjamas, Pyjs, Pyodide,
    Pypy.js, Pystachio, Pythonium, PythonJS,
    PythonScript, PyvaScript, PYXC-PJ,
    RapydScript, Rusthon, Skulpt, Transcrypt

    View Slide

  11. Updated within 1 year
    Batavia, Brython, Bulbul, Empythoned,
    FiddleSalad, Flexx, JavaScripthon, Jiphy, PJs,
    py2js, PyCow, Pyjaco, Pyjamas, Pyjs, Pyodide,
    Pypy.js, Pystachio, Pythonium, PythonJS,
    PythonScript, PyvaScript, PYXC-PJ,
    RapydScript, Rusthon, Skulpt, Transcrypt

    View Slide

  12. General availability
    Batavia, Brython, Bulbul, Empythoned,
    FiddleSalad, Flexx, JavaScripthon, Jiphy, PJs,
    py2js, PyCow, Pyjaco, Pyjamas, Pyjs, Pyodide,
    Pypy.js, Pystachio, Pythonium, PythonJS,
    PythonScript, PyvaScript, PYXC-PJ,
    RapydScript, Rusthon, Skulpt, Transcrypt

    View Slide

  13. Brython
    • https://brython.info/
    • A Python 3 implementation for client-side
    web programming.
    • Embed script in HTML using MIME type
    "text/python".

    View Slide

  14. Brython Sample



    <br/>from browser import document, alert<br/>def echo(ev):<br/>alert("Hello {} !".format(document["zone"].value))<br/>document["test"].bind("click", echo)<br/>
    Your name is :
    click !


    View Slide

  15. Transcrypt
    • https://www.transcrypt.org/
    • Transcrypt is a tool to compile a fairly
    extensive subset of Python into compact,
    readable JavaScript.

    View Slide

  16. Different batteries
    • https://www.transcrypt.org/docs/html/
    what_why.html#the-ecosystem-different-
    batteries
    • Python’s batteries are desktop c.q. server
    batteries. And Transcrypt is for the web client
    world. So it needs different batteries.

    View Slide

  17. Histroy of Transcrypt
    %BUF 7FSTJPO /PUF


    BMQIB
    BMQIB

    View Slide

  18. Histroy of Transcrypt
    %BUF 7FSTJPO /PUF


    BMQIB
    BMQIB
    3$
    3$
    3$
    (FOFSBMBWBJMBCJMJUZ

    View Slide

  19. 3. About Transcrypt

    View Slide

  20. Installation
    $ pip install transcrypt

    View Slide

  21. Transcompile
    $ transcrypt -b

    View Slide

  22. Hello world in Python
    print('Hello, PyCon JP 2018')

    View Slide

  23. Hello world in JavaScript?
    console.log('Hello, PyCon JP 2018');

    View Slide

  24. Hello world in JavaScript
    import {......, print, ......}
    from './org.transcrypt.__runtime__.js';
    var __name__ = '__main__';
    print ('Hello, PyCon JP 2018');

    View Slide

  25. org.transcrypt.__runtime__.js (1)
    AssertionError, AttributeError, BaseException,
    DeprecationWarning, Exception, IndexError,
    IterableError, KeyError, NotImplementedError,
    RuntimeWarning, StopIteration, UserWarning,
    ValueError, Warning

    View Slide

  26. org.transcrypt.__runtime__.js (2)
    __JsIterator__, __PyIterator__, __Terminal__, __add__, __and__,
    __call__, __class__, __envir__, __eq__, __floordiv__, __ge__,
    __get__, __getcm__, __getitem__, __getslice__, __getsm__, __gt__,
    __i__, __iadd__, __iand__, __idiv__, __ijsmod__, __ilshift__,
    __imatmul__, __imod__, __imul__, __in__, __init__, __ior__,
    __ipow__, __irshift__, __isub__, __ixor__, __jsUsePyNext__,
    __jsmod__, __k__, __kwargtrans__, __le__, __lshift__, __lt__,
    __matmul__, __mergefields__, __mergekwargtrans__, __mod__,
    __mul__, __ne__, __neg__, __nest__, __or__, __pow__, __pragma__,
    __proxy__, __pyUseJsNext__, __rshift__, __setitem__,
    __setproperty__, __setslice__, __sort__, __specialattrib__, __sub__,
    __super__, __t__, __terminal__, __truediv__, __withblock__, __xor__

    View Slide

  27. org.transcrypt.__runtime__.js (3)
    abs, all, any, assert, bool, bytearray, bytes,
    callable, chr, copy, deepcopy, delattr, dict, dir,
    divmod, enumerate, filter, float, getattr, hasattr,
    input, int, isinstance, issubclass, len, list, map,
    max, min, object, ord, pow, print, property,
    py_TypeError, py_iter, py_metatype, py_next,
    py_reversed, py_typeof, range, repr, round, set,
    setattr, sorted, str, sum, tuple, zip

    View Slide

  28. List comprehension
    // l = [i * 2 for i in range(10)]
    export var l = (function () {
    var __accu0__ = [];
    for (var i = 0; i < 10; i++) {
    __accu0__.append (i * 2);
    }
    return __accu0__;
    }) ();

    View Slide

  29. Generator comprehension
    // g = (i * 2 for i in range(10))
    export var g = (function () {
    var __accu0__ = [];
    for (var i = 0; i < 10; i++) {
    __accu0__.append (i * 2);
    }
    return py_iter (__accu0__);
    }) ();

    View Slide

  30. yield
    // def y():
    // for i in range(10):
    // yield i * 2
    export var y = function* () {
    for (var i = 0; i < 10; i++) {
    yield i * 2;
    }
    };

    View Slide

  31. Support
    • Python syntax
    • Some standard libraries can’t be imported...
    • Optional static typechecking
    • Source maps
    • Built-in minification

    View Slide

  32. Build with type validation
    $ transcrypt -b -ds

    View Slide

  33. Static type validation
    def concat(a: str, b: str) -> str:
    return f"{a}-{b}"
    # return "33-4"
    concat("33", "4")
    # error: Argument 1 to "concat" has
    # incompatible type "int"; expected "str"
    concat(33, 4)

    View Slide

  34. Generics
    from typing import TypeVar
    AnyStr = TypeVar('AnyStr', str, bytes)
    def concat(a: AnyStr, b: AnyStr) -> AnyStr:
    return a + '-' + b
    # error: Value of type variable
    # "AnyStr" of "concat" cannot be "int"
    concat(33, 4)

    View Slide

  35. 4. Transcrypt with
    JavaScript package

    View Slide

  36. jQuery
    • Transcrypt and jQuery wear well together.
    • '$' can’t be used in Python.
    • Use 'jQuery' or alias.

    View Slide

  37. jQuery sample
    __pragma__('alias', 'S', '$')
    def load_data(url):
    S.ajax({
    'url': url,
    'type': 'GET',
    }).done(
    success_load_data
    ).fail(
    lambda d: alert('Error!')
    )
    def success_load_data(data):
    # Data processing...

    View Slide

  38. Vue.js
    • "new" of JavaScript is required.
    • Operation of "this" is required.

    View Slide

  39. Vue.js sample
    def on_click():
    this.count += 1
    methods = {
    'onClick': on_click
    }
    app = __new__(Vue({
    el: '#app',
    data: {'count': 0},
    methods: methods,
    }))

    View Slide

  40. Angular
    • Give up and use TypeScript.

    View Slide

  41. React / React Native
    • JSX -> React.createElement.
    • Or use 'xtrans' pragma.

    View Slide

  42. xtrans sample
    __pragma__ ('xtrans', 'jsx-transform', '{}', """
    Hello, {this.props.name}
    """)

    View Slide

  43. 4.5 Bonus track

    View Slide

  44. The del statement
    a = "data"
    # a => undefined
    del a

    View Slide

  45. The del statement at list (1)
    a = [0, 1, 2]
    # Python: a => [0, 2]
    # Transcrypt: a => [0, undefined, 2]
    del a[1]

    View Slide

  46. The del statement at list (2)
    a = [0, 1, 2, 3, 4]
    # Python: a => [0, 3, 4]
    # Transcrypt: Parse error.
    del a[1:3]

    View Slide

  47. 5. Summary

    View Slide

  48. Summary
    • Transcrypt almost cover Python syntax.
    • Some standard libraries can’t be imported.
    • Transcrypt and jQuery wear well together.
    • Let's write the front-end in Python.

    View Slide

  49. Thank you for your attention.
    Any questions?

    View Slide