(just my online braindump for Python stuff)
 # id (..) -> Returns address of object
 >>> a=1
 >>> id(a)
 135887080
 >>> b=2
 >>> id(b)
 135887068
 >>> b=1
 >>> id(b) # same as id(a)! Clever python...
 135887080
 >>> a="1"
 >>> id(a)
 3081563808L
 >>> b=chr(ord("1")) 
 >>> b
 '1'
 >>> id(b) # same as id(a)! Clever python...
 3081563808L
 
 # hex, int, float
 >>> hex(160)
 '0xa0'
 >>> int("A0", 16)
 160
 >>> int("0xAA", 16)
 170
 >>> float("1.2")
 1.2
 
 # 'is' checks that identities (id) are the same
 # so this comparison is True:
 if type("1") is type("2") ...  
 
 # complex numbers
 >>> a=1+3j    
 >>> a.real    
 1.0
 >>> a.imag
 3.0
 
 # reversed -> reverse_iterator of x
 >>> a=range(1,10)
 >>> [x for x in reversed(a)]   
 [9, 8, 7, 6, 5, 4, 3, 2, 1]
 # Do it with slice notation
 >>> a[9::-1]
 [9, 8, 7, 6, 5, 4, 3, 2, 1]
 
 # sorted(x) -> sorted copy of x
 >>> a=[4,3,1,2]
 >>> [x for x in sorted(a)]
 [1, 2, 3, 4]
 >>> a
 [4, 3, 1, 2]
 
 # chr, unichr and ord
 >>> chr(183)
 '\xb7'
 >>> ord(chr(183))
 183
 >>> chr(1232)
 Traceback (most recent call last):
   File "<stdin>", line 1, in ?
 ValueError: chr() arg not in range(256)
 >>> unichr(1232)
 u'\u04d0'
 >>> ord(unichr(1232))
 1232
 >>> unicode("aha")
 u'aha'
 
 # singleton Tuples:
 >>> (1)
 1
 >>> (1,)
 (1,)
 
 # slices are l-values
 >>> a=[1,2,3]
 >>> a[1]=1
 >>> a
 [1, 1, 3]
 >>> del(a[1:2])
 >>> a
 [1, 3]
 
 # basestring is the base class for both str and unicode,
 # so instead of using isinstance(a, str) it is better to
 # use isinstance(a, basestring)
 
 # all and any
 >>> all(x%2 for x in xrange(1,10) if x%4)
 False
 >>> any(x%2 for x in xrange(1,10) if x%4)
 True
 
 # enumerate
 for i, value in enumerate(xrange(100,120)):
     print "Index:", i, "value:", value
 
 # sets (and frozensets)
 >>> set((1,2,3))-set([1,3])  
 set([2])
 
 # Always available:
 >>> globals()
 ...
 >>> locals()
 ...
 
 # attribute functions:
 >>> x=1
 >>> hasattr(x, "+")
 False
 >>> hasattr(x, "__add__")
 True
 >>> getattr(x, "__sub__") # same as x.__sub__
 
 # hash
 >>> class A:
 ...    def __init__(self, x):
 ...       self._x = x
 ...    def __hash__(self):
 ...       return hash(self._x)
 ... 
 >>> a = A(1)
 >>> hash(a)
 1
 >>> hash(1)
 1
 >>> a = A("1")
 >>> hash(a)
 1977051568
 >>> hash("1")
 1977051568
 
 >>> raw_input("Oleio:")
 Oleio:data
 'data'
 
 # iter takes a callable and a sentinel value:
 # (also: the only way to implement local scope static variables)
 >>> def tst(f=[0]):
 ...    f[0] += 1
 ...    return f[0]
 ... 
 >>> [x for x in iter(tst, 6)]
 [1, 2, 3, 4, 5]
 
 # list creates a copy, just like [:]
 >>> a=[1,2,3,4]
 >>> id(a)
 -1211132436
 >>> b=a
 >>> id(b)
 -1211132436
 >>> b=list(a)
 >>> id(b)
 -1267617716
 
 # staticmethod
 class A:
     @staticmethod
     def NoSelfReceived(arg1, arg2, ...):
        ...
 
 # from 8859-7 to UTF-8:
 for line in open(sys.argv[1], "r").readlines():
     sys.stdout.write(unicode(line, "iso-8859-7").encode("UTF-8"))
 
 >>> zip([1,2,3], [4,5,6])
 [(1, 4), (2, 5), (3, 6)]
 
 # apply(function, args, keywords) -> function(*args, **keywords)
 
 >>> from __future__ import print_function
 (turns print from a statement into a function, so...)
 >>> map(lambda x: print(x), xrange(1,10))
 
 >>> from fractions import Fraction
 >>> a = Fraction(2, 3)
 >>> b = Fraction(2, 5)
 >>> print a+b

 # Group lists into chunks via use of zip (or better, itertools.izip_longest)
 >>> a=[1,2,3,4,5,6,7,8,9,10,11]
 >>> [iter(a)]*4
 [<listiterator object at 0xb744a98c>, <listiterator object at 0xb744a98c>, 
  <listiterator object at 0xb744a98c>, <listiterator object at 0xb744a98c>]
 >>> zip(*[iter(a)]*4)
 [(1, 2, 3, 4), (5, 6, 7, 8)]
 >>> for j in itertools.izip_longest(*[iter(a)]*4): print j
 (1, 2, 3, 4)
 (5, 6, 7, 8)
 (9, 10, 11, None)

 # Keep unique values
 list(set(x))

 # Offer files from a folder via HTTP
 python -m SimpleHTTPServer

 # Enumerated values
 >>> class Enum(object):
         def __init__(self, *args):
             self.__dict__.update(zip(args, range(len(args))))

 >>> colors = Enum("Red", "Green", "Blue")
 >>> colors.Green
 1
 >>> colors.Blue
 2

 # histogram via defaultdict

 from collections import defaultdict
 d = defaultdict(int)
 for item in xrange(100):
     d[random.randint(0,20)] += 1
Python 2.6 introduces class decorators. This allows us to alter the behaviour of all (or some) methods via a simple '@decorator' syntax. For example, if we want to add logging of all calls made to a class's methods, we simply need this code:
#!/usr/bin/env python2.6

# Python 2.6 allows for class decorators...
# This allows us to alter the behaviour of methods
# just by prepending a class declaration with a @whatever...

# This is an example "logging" decorator


def DecorateFunction(f):
    def logged(*args, **kwargs):
        print "======="
        print "Method", f.func_name, "was called"
        print "args  :", str(*args[1:])
        print "kwargs:", str(**kwargs)
        print "======="
        f(*args, **kwargs)
    return logged


def DecorateClass(x):
    for i, j in x.__dict__.items():
        if hasattr(j, 'func_code'):
            x.__dict__[i] = DecorateFunction(j)
    return x

# This is the user code...


@DecorateClass
class A:
    def __init__(self):
        self._x = 1

    def Print(self):
        print self._x

    def IncreaseBy(self, y):
        self._x += y

if __name__ == "__main__":
    a = A()
    a.IncreaseBy(5)
    a.Print()
    a.IncreaseBy(11)
    a.Print()


profile for ttsiodras at Stack Overflow, Q&A for professional and enthusiast programmers
GitHub member ttsiodras
 
Index
 
 
CV
 
 
Updated: Wed Oct 29 18:55:50 2008