Impressive Python Syntax

list comprehension

PEP 202 -- List Comprehensions

[n for n in range(10) if n % 2 == 0]

sample:

import re
lst = sum(re.findall('\d+', line) for line in open('lines.txt'), [])

generator

PEP 289 -- Generator Expressions

def gen(n=0):
    while True:
        yield n
        n += 1

sample:

import urllib
def integers_on_web():
    for page in range(10):
        conn = urllib.urlopen('http://example.com/integer?page=%s' % page)
        for n in conn.readlines():
            yield int(n)
        conn.close()

for n in integers_on_web():
    print n

ternary operator

PEP 308 -- Conditional Expressions

x = int(input_raw())
y = 1 if x < 0 else 1

sample:

def pow(x, y):
    return [lambda: pow(x, y/2)**2, lambda: 1][1 if y < 2 else 0]() * [1, x][y % 2]

for - else

PEP 315 -- Enhanced While Loop

for cond in conditions:
    if not cond:
        break
else:
    print 'passed all case'

sample:

# sample 1
def isprime(n):
    if n < 2:
        return False
    for i in xrange(2, int(sqrt(n) + 1)):
        if n % i == 0:
            break
    else:
        return True
    return False

try - else

PEP 341 -- Unifying try-except and try-finally

try:
    do()
except Exception, e:
    print e
else:
    print 'exception was not throwed'

sample:

# sample: database transaction
conn = None
try:
    conn = connect_database()
    conn.begin()
    for q in queries:
        conn.execute(q)
except Exception, e:
    if conn is not None:
        conn.rollback()
else:
    conn.commit()
finally:
    if conn is not None:
        conn.close()

decorator

PEP 318 -- Decorators for Functions and Methods

@deco
def f(n):
    return n + 1

sample:

#
# sample 1: function memoization
#
def memoize(fn):
    cache = {}
    def gn(*args):
        if not args in cache:
            cache[args] = fn(*args)
        return cache[args]
    return gn

def fib(n):
    if n in [0, 1]:
        return n
    else:
        return fib(n-2) + fib(n-1)

@memoize
def mfib(n):
    if n in [0, 1]:
        return n
    else:
        return mfib(n-2) + mfib(n-1)

import time
def doit(fun, n):
    s = time.time()
    fun(n)
    e = time.time()
    return e-s

print "fib  : %.15f sec" % doit(fib, 32)
print "mfib : %.15f sec" % doit(mfib, 32)
# fib  : 2.674999952316284 sec
# mfib : 0.000000000000000 sec

#
# sample 2: django view function http://www.djangoproject.com/
#
@login_required # redirect to login page if not logged in.
def mypage(req):
    res = build_response()
    return res

Arbitrary/Unpacking Argument Lists

Python v2.7.1 documentation - More Control Flow Tools
http://docs.python.org/tutorial/controlflow.html#arbitrary-argument-lists
http://docs.python.org/tutorial/controlflow.html#unpacking-argument-lists

def f(*args): # packing
    x,y = args
    print x,y

def g(x, y):
    return x + y

a = [x, y]
f(*a) # unpacking

sample:

# sample 1: matrix transposition
m = [[1,2,3,4], [5,6,7,8], [9,10,11,12], [13,14,15,16]]
mt = zip(*m)
print mt # => [(1, 5, 9, 13), (2, 6, 10, 14), (3, 7, 11, 15), (4, 8, 12, 16)]

# sample 2: easily extendable function
def fun(*args, **kwargs):
    for arg in args:
        print arg
    for key in kwargs:
        print key,kwargs[key]

account = {
    'username': 'username_a',
    'password': 'password_a',
    'extra': 'info',
}
fun(**account)