Slide 1

Slide 1 text

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

Slide 2

Slide 2 text

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

Slide 3

Slide 3 text

1. Introduction

Slide 4

Slide 4 text

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

Slide 5

Slide 5 text

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

Slide 6

Slide 6 text

2. About altJS

Slide 7

Slide 7 text

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

Slide 8

Slide 8 text

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

Slide 9

Slide 9 text

Python -> JavaScript…!

Slide 10

Slide 10 text

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

Slide 11

Slide 11 text

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

Slide 12

Slide 12 text

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

Slide 13

Slide 13 text

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

Slide 14

Slide 14 text

Brython Sample from browser import document, alert def echo(ev): alert("Hello {} !".format(document["zone"].value)) document["test"].bind("click", echo)

Your name is : click !

Slide 15

Slide 15 text

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

Slide 16

Slide 16 text

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.

Slide 17

Slide 17 text

Histroy of Transcrypt %BUF 7FSTJPO /PUF BMQIB BMQIB

Slide 18

Slide 18 text

Histroy of Transcrypt %BUF 7FSTJPO /PUF BMQIB BMQIB 3$ 3$ 3$ (FOFSBMBWBJMBCJMJUZ

Slide 19

Slide 19 text

3. About Transcrypt

Slide 20

Slide 20 text

Installation $ pip install transcrypt

Slide 21

Slide 21 text

Transcompile $ transcrypt -b

Slide 22

Slide 22 text

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

Slide 23

Slide 23 text

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

Slide 24

Slide 24 text

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

Slide 25

Slide 25 text

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

Slide 26

Slide 26 text

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__

Slide 27

Slide 27 text

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

Slide 28

Slide 28 text

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__; }) ();

Slide 29

Slide 29 text

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__); }) ();

Slide 30

Slide 30 text

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; } };

Slide 31

Slide 31 text

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

Slide 32

Slide 32 text

Build with type validation $ transcrypt -b -ds

Slide 33

Slide 33 text

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)

Slide 34

Slide 34 text

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)

Slide 35

Slide 35 text

4. Transcrypt with JavaScript package

Slide 36

Slide 36 text

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

Slide 37

Slide 37 text

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...

Slide 38

Slide 38 text

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

Slide 39

Slide 39 text

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

Slide 40

Slide 40 text

Angular • Give up and use TypeScript.

Slide 41

Slide 41 text

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

Slide 42

Slide 42 text

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

Slide 43

Slide 43 text

4.5 Bonus track

Slide 44

Slide 44 text

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

Slide 45

Slide 45 text

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

Slide 46

Slide 46 text

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

Slide 47

Slide 47 text

5. Summary

Slide 48

Slide 48 text

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.

Slide 49

Slide 49 text

Thank you for your attention. Any questions?