Here are some tricks, hacks and patterns in Python. I will try to add more as I come across them.
print [item*2 for item in [1, 2, 3]]
# prints: [2, 4, 6]
cond = True
print 'yes' if cond else 'no'
# prints: yes
def somefunc(*args, **kwargs):
print 'args: %s' % str(args)
print 'kwargs: %s' % kwargs
somefunc(1, 2, thirdarg=3)
# prints:
# args: (1, 2)
# kwargs: {'thirdarg': 3}
class SomeClass(object):
def __getattr__(self, fname):
def wrapper(*args, **kwargs):
print fname, args, kwargs
return wrapper
someobj = SomeClass()
someobj.somemethod(1, 2, 3)
# prints: somemethod (1, 2, 3) {}
def get_module(s):
module = __import__(s)
for i in s.split(".")[1:]:
module = getattr(module, i)
return module
module3 = get_module('module1.module2.module3')
class HybridObj(object):
def __getitem__(self, name):
return self.__dict__[name]
def __setitem__(self, name, value):
self.__dict__[name] = value
def set_all(self, dict):
self.__dict__ = dict
def get_all(self):
return self.__dict__
obj = HybridObj()
obj['mykey'] = 'myval'
print obj.mykey
# prints: myval
print obj.get_all()
# prints: {'mykey': 'myval'}
app = App()
while True:
try:
app.main()
except Exception:
import StringIO, traceback
output = StringIO.StringIO()
traceback.print_exc(file=output)
print output.getvalue()
time.sleep(10)
obj = 3.14
if isinstance(obj, basestring):
type = 'string'
elif isinstance(obj, (int, float)):
type = 'number'
else:
type = obj.__class__
print type
# prints: number
def base_amount(value):
def decorator(func):
def wrapper(*args):
a, b = args
a += value
return func(a, b)
return wrapper
return decorator
@base_amount(5)
def add(a, b):
return a + b
print add(3, 4)
# prints: 12
a = [1, 2, 3, 4, 5]
#copy a list
print a[:]
# prints: [1, 2, 3, 4, 5]
#copy in reverse
print a[::-1]
# prints: [5, 4, 3, 2, 1]
print a[1:-1]
# prints: [2, 3, 4]
print a[-2:]
# prints: [4, 5]
print a[:-2]
# prints: [1, 2, 3]
map((lambda x: x*2), [1, 2, 3])
#prints: [2, 4, 6]
reduce(lambda x, y: x+y, [1, 2, 3])
#prints: 6
filter((lambda x: x>2), range(6))
#prints: [3, 4, 5]
student_tuples = [
('john', 'A', 15),
('jane', 'B', 12),
('dave', 'B', 10),
]
print sorted(student_tuples, key=itemgetter(2), reverse=True)
# prints: [('john', 'A', 15), ('jane', 'B', 12), ('dave', 'B', 10)]
# taken from: http://wiki.python.org/moin/HowTo/Sorting/
import threading
global = threading.local()
global.somevar = 3
def somefunc():
return val1, val2
val1, val2 = somefunc()
if 'somestring' in ['this', 'list', 'of', 'strings']:
print 'yes!'
print set(['a', 'b', 'a', 'c'])
# prints: ['a', 'b', 'c']
raise TypeError('Some error about type %s' % (t,))
raise AttributeError('Some error about attr %s' % (a,))
raise ValueError('Some error about val %s' % (v,))