Share
Embed
Transcript
49 slides
-
Python as altJS - Let's write the front-end in Python.
2018-09-18 (PyCon JP 2018) Junya HASEBA -
Contents 1. Introduction 2. About altJS 3. About Transcrypt 4.
Transcrypt with JavaScript package 5. Summary -
Who am I ? • Junya HASEBA (@7pairs) • Android
/ Web engineer • Java / Kotlin • C# • JavaScript -
Advertisement - Sorry, this slide is written in Japanese. •
ٕज़ॻయ5 (10/8 ାαϯγϟΠϯγςΟ) ʹαʔΫϧࢀՃ (͔09) • ʰ΄΅Python͚ͩͰαʔόʔϨεΞϓϦΛͭ͘Ζ͏ʱΛ൦ • Chalice (όοΫΤϯυ) • Transcrypt (ϑϩϯτΤϯυ) • pytest (Ϣχοτςετ, APIςετ) • Selene (UIςετ) -
What’s altJS ? • Programming languages that transcompiles to JavaScript.
• TypeScript • CoffeeScript • Hexe • etc... -
Other language -> JavaScript • Kotlin/JS (Kotlin) • ClojureScript (Clojure)
• GopherJS (Go) • ShiftJS (Swift) • etc... -
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 -
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 -
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 -
Brython • https://brython.info/ • A Python 3 implementation for client-side
web programming. • Embed script in HTML using MIME type "text/python". -
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> -
Transcrypt • https://www.transcrypt.org/ • Transcrypt is a tool to compile
a fairly extensive subset of Python into compact, readable JavaScript. -
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. -
Histroy of Transcrypt %BUF 7FSTJPO /PUF
BMQIB BMQIB -
Histroy of Transcrypt %BUF 7FSTJPO /PUF
BMQIB BMQIB 3$ 3$ 3$ (FOFSBMBWBJMBCJMJUZ -
Hello world in JavaScript import {......, print, ......} from './org.transcrypt.__runtime__.js';
var __name__ = '__main__'; print ('Hello, PyCon JP 2018'); -
org.transcrypt.__runtime__.js (1) AssertionError, AttributeError, BaseException, DeprecationWarning, Exception, IndexError, IterableError, KeyError,
NotImplementedError, RuntimeWarning, StopIteration, UserWarning, ValueError, Warning -
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__ -
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 -
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__; }) (); -
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__); }) (); -
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; } }; -
Support • Python syntax • Some standard libraries can’t be
imported... • Optional static typechecking • Source maps • Built-in minification -
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) -
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) -
jQuery • Transcrypt and jQuery wear well together. • '$'
can’t be used in Python. • Use 'jQuery' or alias. -
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... -
Vue.js • "new" of JavaScript is required. • Operation of
"this" is required. -
Vue.js sample def on_click(): this.count += 1 methods = {
'onClick': on_click } app = __new__(Vue({ el: '#app', data: {'count': 0}, methods: methods, })) -
React / React Native • JSX -> React.createElement. • Or
use 'xtrans' pragma. -
The del statement at list (1) a = [0, 1,
2] # Python: a => [0, 2] # Transcrypt: a => [0, undefined, 2] del a[1] -
The del statement at list (2) a = [0, 1,
2, 3, 4] # Python: a => [0, 3, 4] # Transcrypt: Parse error. del a[1:3] -
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.