altJSとしてのPython / PyCon JP 2018

6fa3836d10d691125749472297cf516a?s=47 7pairs
September 18, 2018

altJSとしてのPython / PyCon JP 2018

6fa3836d10d691125749472297cf516a?s=128

7pairs

September 18, 2018
Tweet

Transcript

  1. Python as altJS - Let's write the front-end in Python.

    2018-09-18 (PyCon JP 2018) Junya HASEBA
  2. Contents 1. Introduction 2. About altJS 3. About Transcrypt 4.

    Transcrypt with JavaScript package 5. Summary
  3. 1. Introduction

  4. Who am I ? • Junya HASEBA (@7pairs) • Android

    / Web engineer • Java / Kotlin • C# • JavaScript
  5. Advertisement - Sorry, this slide is written in Japanese. •

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

  7. What’s altJS ? • Programming languages that transcompiles to JavaScript.

    • TypeScript • CoffeeScript • Hexe • etc...
  8. Other language -> JavaScript • Kotlin/JS (Kotlin) • ClojureScript (Clojure)

    • GopherJS (Go) • ShiftJS (Swift) • etc...
  9. Python -> JavaScript…!

  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
  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
  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
  13. Brython • https://brython.info/ • A Python 3 implementation for client-side

    web programming. • Embed script in HTML using MIME type "text/python".
  14. Brython Sample <!DOCTYPE html> <html> <body onload="brython(1)"> <script type="text/python"> from

    browser import document, alert def echo(ev): alert("Hello {} !".format(document["zone"].value)) document["test"].bind("click", echo) </script> <p>Your name is : <input id="zone" autocomplete="off"> <button id="test">click !</button> </body> </html>
  15. Transcrypt • https://www.transcrypt.org/ • Transcrypt is a tool to compile

    a fairly extensive subset of Python into compact, readable JavaScript.
  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.
  17. Histroy of Transcrypt %BUF 7FSTJPO /PUF    

      BMQIB   BMQIB
  18. Histroy of Transcrypt %BUF 7FSTJPO /PUF    

      BMQIB   BMQIB   3$   3$   3$   (FOFSBMBWBJMBCJMJUZ
  19. 3. About Transcrypt

  20. Installation $ pip install transcrypt

  21. Transcompile $ transcrypt -b <target>

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

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

  24. Hello world in JavaScript import {......, print, ......} from './org.transcrypt.__runtime__.js';

    var __name__ = '__main__'; print ('Hello, PyCon JP 2018');
  25. org.transcrypt.__runtime__.js (1) AssertionError, AttributeError, BaseException, DeprecationWarning, Exception, IndexError, IterableError, KeyError,

    NotImplementedError, RuntimeWarning, StopIteration, UserWarning, ValueError, Warning
  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__
  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
  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__; }) ();
  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__); }) ();
  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; } };
  31. Support • Python syntax • Some standard libraries can’t be

    imported... • Optional static typechecking • Source maps • Built-in minification
  32. Build with type validation $ transcrypt -b -ds <target>

  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)
  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)
  35. 4. Transcrypt with JavaScript package

  36. jQuery • Transcrypt and jQuery wear well together. • '$'

    can’t be used in Python. • Use 'jQuery' or alias.
  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...
  38. Vue.js • "new" of JavaScript is required. • Operation of

    "this" is required.
  39. Vue.js sample def on_click(): this.count += 1 methods = {

    'onClick': on_click } app = __new__(Vue({ el: '#app', data: {'count': 0}, methods: methods, }))
  40. Angular • Give up and use TypeScript.

  41. React / React Native • JSX -> React.createElement. • Or

    use 'xtrans' pragma.
  42. xtrans sample __pragma__ ('xtrans', 'jsx-transform', '{}', """ <div>Hello, {this.props.name}</div> """)

  43. 4.5 Bonus track

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

    del a
  45. The del statement at list (1) a = [0, 1,

    2] # Python: a => [0, 2] # Transcrypt: a => [0, undefined, 2] del a[1]
  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]
  47. 5. Summary

  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.
  49. Thank you for your attention. Any questions?