Wednesday, October 14, 2009

python best practices

http://www.fantascienza.net/leonardo/ar/python_best_practices.html

# Python profiler:
python -m profile -o stats myscript.py
>>> import pstats
>>> p = pstats.Stats('stats')
>>> p.sort_stats('time').print_stats(15)

# For source code with not 7-bit ASCII
add this on top:
# -*- coding: UTF-8 -*-
# Or just, if you have less memory:
# coding: latin

# Use iter* methods when possible
mapping = {5: "5", 6: "6"}
for key, val in mapping.iteritems(): ...
for key in mapping: ...

a = 5
b = 6
a, b = b, a # swap

a = b = c = 5

if x == 1: y = fun1(x)
elif x == 2: y = fun2(x)
elif x == 3: y = fun3(x)
else: y = None
# But sometimes a dict is better:
funs = {1: fun1, 2: fun2, 3: fun3}
y = funs.get(x, lambda x:None)(x)

def mul(x, y):
return x * y
l = [2, 3]
print mul(*l)

# Generally getters and setters are not used.
# Instance names starting with _ are meant as
# 'to not mess with' by convention.
# Instance names starting with __ are private
# and receive name mangling.
class Foo(object):
def __init__(self, x, y, z):
self.x_public = x
self._y_private = y
self.__z_veryprivate = z
print Foo(1, 2, 3).x_public

finder = re.compile(r"""
^ \s* # start at beginning+ opt spaces
( [\[\]] ) # Group 1: opening bracket
\s* # optional spaces
( [-+]? \d+ ) # Group 2: first number
\s* , \s* # opt spaces+ comma+ opt spaces
( [-+]? \d+ ) # Group 3: second number
\s* # opt spaces
( [\[\]] ) # Group 4: closing bracket
\s* $ # opt spaces+ end at the end
""", flags=re.VERBOSE)
# Sometimes it's positive to indent logically those
# lines just like code.

# Sometimes it can be positive to compose REs:
spaces = r"\s*" # optional spaces
number = r"( [-+]? \d+ )" # Group
bracket = r"( [\[\]] )" # Group. Closing bracket
parts = ["^", bracket, number, ",", number, bracket, "$"]
finder = re.compile(spaces.join(parts), flags=re.VERBOSE)


# Use doctests (or module tests):
def function(data):
"""A comment

>>> function()
None
>>> function(1)
result1
>>> function("a")
Traceback (most recent call last):
...
TypeError
"""
...implementation...

if __name__ == "__main__":
import doctest
doctest.testmod()
print "Tests done."


x = (1, 2, 6, 55, 63, 96, 125, 256,
301, 456, 958, 1256,
1359, 2568, 3597)
# Too much long lines must be broken with \
# but \ isn't necessary inside () [] {}



# Using psyco array.array of double and
# signed long become very fast
import array
a = array.array("d", [3.56, 2.12])

No comments: