Client-side Python

Python to JavaScript compiler

Python is a general-purpose, high-level programming language with a readability emphasis. The Python compiler takes on the numerous JavaScript quirks and inconsistencies, the lack of a standard library, and removes the pain resulting from switching between programming languages. Variables no longer have global scope by default. Instead, they must be defined using the keyword global. Testing for equality between two objects does a deep comparison, while truth values are the same as in Python. Class based inheritance replaces prototypal inheritance. In addition, many of the functions in the standard Python library is built-in. The best part is it compiles to JavaScript, so JavaScript libraries such as jQuery can be used directly.

To use the compiled JavaScript, include pylib.js 1.1 before the compiled JavaScript:

            <script type="text/javascript" src="pylib.js"></script>
            <script type="text/javascript" src="script.js"></script>
            

Features

Lists and Tuples
  • indexing, slicing, length, minimum, maximum
  • the list function
  • list methods: append, extend, index, insert, pop, reverse
  • tuples as immutable sequences
Strings
Dictionaries
  • the dict function
        >>> items = [('name', 'Gumby'), ('age', 42)]
        >>> d = dict(items)
        {'age': 42, 'name': 'Gumby'}
        
  • basic operations: d[k] = v, in, del
Conditionals, Loops and Other Statements
  • conditional execution with the if statement, else and elseif clauses
  • ternary statement
        >>> 'true' if True else 'false'
        'true'
        >>> 'true' if False else 'false'
        'false'
        
  • for...in loops
  • with...as scope isolation
  • try...except...finally exception catching
Functions
  • functions support default arguments
  • variables within functions are scoped locally
  • lambda expressions and functional programming support
Classes
  • polymorphism and inheritance
  • getattr, hasattr, isinstance

Standards Compliant Python

Truth Values

Everything except None, False, 0, '', (), [], {} are true. Dictionaries compare equal if and only if their key-value pairs are equal.

    >>> moe   = {'name': 'moe'}
    >>> clone = {'name': 'moe'}
    >>> moe == clone
    True
    >>> moe is clone #https://docs.python.org/library/stdtypes.html#comparisons
    False
    >>> moe['name'] = 'joe'
    >>> moe == clone
    False
    

List Comprehensions

    >>> l = [(x, y) for x in range(3) for y in range(3)]
    [(0, 0), (0, 1), (0, 2), (1, 0), (1, 1), (1, 2), (2, 0), (2, 1), (2, 2)]

Examples

JavaScript Specifc Enhancements

Unquoted Dictionary Keys

Dictionaries can be created without quoting keys

    >>> phonebook_shorthand = {Alice: '2341', Beth: '9102', Cecil: '3258'}
    ... phonebook = {'Alice': '2341', 'Beth': '9102', 'Cecil': '3258'}
    ... phonebook_shorthand == phonebook
    True
        

Scope Isolation

Any time you need to define a separate scope for each value in a collection, with ... as can be used to isolate each iteration through the collection. In a situation involving multiple AJAX calls with different parameters, a context often needs to be associated each callback.

    >>> keys = ["a", "b"]
    ... for index in keys:
    ...     with keys[index] as key:
    ...         $.ajax({
    ...             url: 'test.json',
    ...             type: 'GET',
    ...             dataType: 'json',
    ...             success: def(data, textStatus, XMLHttpRequest):
    ...                 print key
    ...         })
    a
    b
    

Checking for Undefined

The standard Python approach for testing if a variable is defined and initialized is unwieldy. However, a simple if statement is enough to test if a variable has been defined in the browser implementation of Python:

    >>> if not a:
    ...     a = 1
    ... print a
    1

Looping Through jQuery Elements

Native jQuery returns a list of DOM elements, which is iterable with afor loop. Suppose we had an image gallery and wanted to position the images:

    >>> pic = $('#images a')
    ... pic.hide()
    ... for i, next in pic:
    ...     next.css({'position': 'absolute','left':65*i})
    ...     next.show()
    
Next refers to the jQuery object for the current element. The more concise Python syntax avoids the use of $(this).

Notes and Caveats

  • Python keywords such as list and dict should not be used as variable or function names
  • The function JS is for embedded JavaScript and takes a string
  • pylib.js needs to be loaded before other compiled scripts
  • The _ namespace is reserved for the underscore JavaScript library
  • Methods and functions common between Python and JavaScript behave as they do in Python