Ertug Karamatli / pages / lang /

Common Python Patterns




Here are some tricks, hacks and patterns I like using most while coding Python. I will try to add more when I come across them.

Basic One-Liners

print [item*2 for item in [1, 2, 3]]
# prints: [2, 4, 6]

cond = True
print 'yes' if cond else 'no'
# prints: yes

Dynamic Function Arguments

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}

Pseudo Methods

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) {}

Dynamic Imports

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')

Object-Dict Hybrid

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'}

Error Recovery Pattern

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)

Type Checking

obj = 3.14

if isinstance(obj, basestring):
    type = 'string'
elif isinstance(obj, (int, float)):
    type = 'number'
else:
    type = obj.__class__

print type
# prints: number

Decorators

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

Slice Notation

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]

Functional style

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]

Sorting according to a key

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/

Getting items from a dictionary according to a pattern

items = {
    'name': lambda x: x['user']['name'],
    'post_count': lambda x: x['posts']['count'],
}
dct = {
    'user': {
        'name': 'Someone',
    },
    'posts': {
        'count': 5,
    },
}

new_dct = {}
for n, fn in items.iteritems():
    new_dct[n] = fn(dct)

print new_dct
# prints: {'post_count': 5, 'name': 'Someone'}

Global Variables in Threads

import threading
global = threading.local()
global.somevar = 3

Multi-value return

def somefunc():
    return val1, val2

val1, val2 = somefunc()

Checking if a value exists in a list

if 'somestring' in ['this', 'list', 'of', 'strings']:
    print 'yes!'

Removing duplicate items in a list

print set(['a', 'b', 'a', 'c'])
# prints: ['a', 'b', 'c']

Raising Meaningful Errors

raise TypeError('Some error about type %s' % (t,))
raise AttributeError('Some error about attr %s' % (a,))
raise ValueError('Some error about val %s' % (v,))

Updates

I have got some comments on Python reddit. I have fixed the errors, they are now working. I should have checked them, thanks for pointing them out!


blog comments powered by Disqus


If you liked the article you can subscribe to the RSS feed or share:
Creative Commons License