view PythonForJsProgrammers.txt @ 0:027bea439a55

Origination.
author Atul Varma <varmaa@toolness.com>
date Thu, 05 Jun 2008 14:21:46 -0700
parents
children ea010fae8754
line wrap: on
line source

=================================
Python for JavaScript Programmers
=================================

I couldn't find anything on the web that attempted to teach Python to
readers who already knew JavaScript, so I thought I'd give it a shot,
since a number of my friends at Mozilla don't know much about Python
but know JavaScript incredibly well.  The languages actually aren't
that dissimilar--in fact, some of JavaScript's latest features have
been `borrowed directly from Python`_.

.. _`borrowed directly from Python`: http://weblogs.mozillazine.org/roadmap/archives/2006/02/js_and_python_news.html

Interactive Shell
=================

Python, when executed with no parameters, just presents an interactive
shell.  It's similar to the SpiderMonkey shell and xpcshell if you're
familiar with those.  The code examples in this tutorial will be
displayed as though they're being executed in it, like so:

    >>> 1 + 2
    3
    >>> # Here's a comment that does nothing.
    >>> print "hi!"
    hi!
    >>> print "This is a long " \
    ...       "statement that spans multiple lines."
    This is a long statement that spans multiple lines.

The shell is also a useful way to explore Python's functionality; feel
free to just use it as a desk calculator to get used to it.

No Brackets
===========

Python doesn't have brackets; instead, indentation alone is used to
lay out blocks of code.  For instance:

    >>> if 1 == 2:
    ...   print "Something very strange is going on."
    ...   print "Right now."
    ... else:
    ...   print "The world is fine."
    The world is fine.

No Semicolons
=============

As with JavaScript, semicolons are actually optional.  Whereas always
using semicolons is the accepted stylistic standard in JS, however,
it's the reverse in Python: don't ever use them.

Functions
=========

Functions are defined like so:

    >>> def foo(x):
    ...     print "foo called with parameter: %s" % x

They are called as you'd expect:

    >>> foo(5)
    foo called with parameter: 5

As in Javascript, they're first-class citizens and can be passed
around as parameters to other functions and so forth.

Closures
========

Function closures are available in Python:

    >>> def myfunc():
    ...     a = 1
    ...     def wrapped():
    ...         return a
    ...     return wrapped
    >>> myfunc()()
    1

Unlike Javascript, however, the variable bindings in the closure are
"read-only":

    >>> def myfunc():
    ...     a = 1
    ...     def wrapped():
    ...         a += 1                 # Doesn't work!
    ...         return a
    ...     return wrapped
    >>> myfunc()()
    Traceback (most recent call last):
    ...
    UnboundLocalError: local variable 'a' referenced before assignment

This means that closures can't be used to access private variables
like they can in JavaScript; instead, everything is visible, and
implementation-specific variables are conventionally preceded with one
or two underscores.

Lists
=====

Lists are a lot like JavaScript arrays.  Iterating through them is
easy:

    >>> mylist = ["hello", "there"]
    >>> for i in mylist:
    ...     print i
    hello
    there

Tuples are just like lists, only they're immutable and differentiated
from lists by using parentheses instead of brackets:

    >>> mytuple = ("hello", "there")
    >>> mytuple[0] = "bye"
    Traceback (most recent call last):
    ...
    TypeError: 'tuple' object does not support item assignment

Tuples with a single item look a little weird, though:

    >>> mytuple = ("hello",)   # Without the comma, it'd just be a string.

It's not possible for there to be "holes" in Python arrays like there
are in Javascript ones, though:

    >>> a = [1, 2, 3]
    >>> del a[1]               # Deletes '2'
    >>> a
    [1, 3]

Indexing and Slicing
====================

Any item that is a sequence can be indexed as expected, but unlike
Javascript, negative indexes may be used to denote items from the end
of the sequence:

    >>> ["hello", "there", "dude"][-1]
    'dude'

Any indexable item can generally also be sliced; this is similar to
``String.slice`` in JavaScript, only built-in to the language:

    >>> "hello"[2:4]     # Just like "hello".slice(2,4) in JS
    'll'

    >>> "hello"[2:]      # Just like "hello".slice(2) in JS
    'llo'

    >>> "hello"[:4]      # Just like "hello".slice(0,4) in JS
    'hell'

Dictionaries
============

Dictionaries are a lot like Object literals in JavaScript:

    >>> d = {"foo" : 1, "bar" : 2}
    >>> d["foo"]
    1

Their properties can't be referenced using dot notation, though:

    >>> d.foo
    Traceback (most recent call last):
    ...
    AttributeError: 'dict' object has no attribute 'foo'

Dictionaries generally aren't used to create arbitrary objects like
they are in Javascript, though; they don't have prototypes, nor do
they have meta-methods.  Instead, classes are used to do that sort of
thing.

Classes
=======

Classes are pretty straightforward:

    >>> class Foo(object):
    ...     def __init__(self, a):
    ...         self.a = a
    ...         print "Foo created."
    ...     def doThing(self):
    ...         return self.a + 1

Here ``Foo`` is a subclass of ``object``, which is the root object
class that any class should ultimately descend from.  The constructor
is always called ``__init__()`` and is invoked like so:

    >>> f = Foo(1)
    Foo created.

So you don't need to use a ``new`` operator or anything as is the case
with JS.  Calling methods and accessing attributes is straightforward
too:

    >>> f.a
    1
    >>> f.doThing()
    2

Classes in Python get inheritance for free, but because they're not
really prototype-based, it's not easy to dynamically add or remove
methods to existing objects on-the-fly.

An object's methods are also bound to the object itself, so--unlike in
Javascript--if they're "disconnected" from the object, they still work:

    >>> f = Foo(5)
    Foo created.
    >>> doThing = f.doThing
    >>> doThing()
    6

Coding Style
============

Python has a coding convention that's generally been embraced
throughout the community; almost all libraries use it.  It's contained
in `PEP 8`_.

.. _`PEP 8`: http://www.python.org/dev/peps/pep-0008