Skip to content

Instantly share code, notes, and snippets.

@svalleru
Last active April 6, 2016 06:13
Show Gist options
  • Save svalleru/a1c41d2eae7ac6ed03d3 to your computer and use it in GitHub Desktop.
Save svalleru/a1c41d2eae7ac6ed03d3 to your computer and use it in GitHub Desktop.
Python Idioms
__author__ = 'svalleru'
# Monkey patching
class Spam(object):
def __init__(self, name):
self._name = name
def beans(self):
print "Good morning, %s. Here are your delicious fried beans." % (self._name,)
s = Spam('Mrs. Higgs')
s.beans()
def beans_with_pepper(self):
print "Hello, %s. Enjoy your fried beans with perpper" % (self._name,)
Spam.beans = beans_with_pepper # monkey patch the class
s.beans()
# Good morning, Mrs. Higgs. Here are your delicious fried beans.
# Hello, Mrs. Higgs. Enjoy your fried beans with perpper
# ===
# List comprehensions
fruits = ['watermelon', 'apple', 'mango', 'kiwi', 'apricot', 'lemon', 'guava']
values = [2, 42, 18, 92, "boom", ['a', 'b', 'c']]
ufruits = [fruit.upper() for fruit in fruits]
afruits = [fruit for fruit in fruits if fruit.startswith('a')]
doubles = [v * 2 for v in values]
print "ufruits:", " ".join(ufruits)
print "afruits:", " ".join(afruits)
print "doubles:",
for d in doubles:
print d,
# ufruits: WATERMELON APPLE MANGO KIWI APRICOT LEMON GUAVA
# afruits: apple apricot
# doubles: 4 84 36 184 boomboom ['a', 'b', 'c', 'a', 'b', 'c']
# ===
# More list comps
x, y, z, n = (int(input()) for _ in range(4))
print ([[a,b,c] for a in range(0,x+1) for b in range(0,y+1) for c in range(0,z+1) if a + b + c != n ])
#stdin:
#1
#1
#1
#2
#stdout: [[0, 0, 0], [0, 0, 1], [0, 1, 0], [1, 0, 0], [1, 1, 1]]
# Sort with lambda key
fruits = ['watermelon', 'Apple', 'Mango', 'KIWI', 'apricot', 'LEMON', 'guava']
sfruits = sorted(fruits, key=lambda e: e.lower())
print " ".join(sfruits)
# Apple apricot guava KIWI LEMON Mango watermelon
d = {"keyword1": 3, "keyword2": 1, "keyword3": 5, "keyword4": 2}
print sorted(d, key=d.get, reverse=False)
# ['keyword2', 'keyword4', 'keyword1', 'keyword3']
# ===
# Decorator method
def debugger(old_func):
def new_func(*args, **kwargs):
print "*" * 40
print "** function", old_func.__name__, "**"
if args:
print "\targs are ", args
if kwargs:
print "\tkwargs are ", kwargs
print "*" * 40
old_func(*args, **kwargs) # call the 'real' function
return new_func # return the new function object
@debugger
def hello(greeting, whom):
print "%s, %s" % (greeting, whom)
hello('hello', 'world')
hello('hi', 'Earth')
# ****************************************
# ** function hello **
# args are ('hello', 'world')
# ****************************************
# hello, world
# ****************************************
# ** function hello **
# args are ('hi', 'Earth')
# ****************************************
# hi, Earth
# ===
# Decorator class
class debugger(object):
def __init__(self, phase=None, release=None):
self._phase = phase
self._release = release
def __call__(self, oldf):
def newf(*args, **kwargs):
print
print "*" * 40
print "** function", oldf.__name__, "**"
print "{0}: {1}".format(self._phase, self._release)
print "*" * 40
return oldf(*args, **kwargs)
return newf
@debugger('phase I', 'FINAL')
def hello(greeting, whom):
print "%s, %s" % (greeting, whom)
hello('hello', 'world')
hello('hi', 'Earth')
# ****************************************
# ** function hello **
# phase I: FINAL
# ****************************************
# hello, world
#
# ****************************************
# ** function hello **
# phase I: FINAL
# ****************************************
# hi, Earth
# ===
# Looping idioms
from itertools import izip
names = 'jack jim jill'.split()
colors = 'red blue yellow green'.split()
for name in names:
print name.capitalize()
# Jack
# Jim
# Jill
for i, name in enumerate(names):
print i, name.capitalize()
# 0 Jack
# 1 Jim
# 2 Jill
for name, color in zip(names, colors):
print name, '-->', color
# jack --> red
# jim --> blue
# jill --> yellow
for name, color in izip(names, colors):
print name, '-->', color
# jack --> red
# jim --> blue
# jill --> yellow
for name in reversed(names):
print name
# jill
# jim
# jack
for name in sorted(names):
print name
# jack
# jill
# jim
for name in sorted(names, key=len):
print name
# jim
# jack
# jill
for name in sorted(names, reverse=True):
print name
# jim
# jill
# jack
d = dict(izip(names, colors))
for name, color in d.iteritems():
print name, '-->', color
# jim --> blue
# jack --> red
# jill --> yellow
# ===
# Sort a Dict based on value
from collections import OrderedDict
d = {v: v ** 2 for v in range(5)}
for k, v in OrderedDict(sorted(d.items(), key=lambda x: x[1], reverse=True)).iteritems():
print k, v
# 4 16
# 3 9
# 2 4
# 1 1
# 0 0
# ===
# Dictionary comprehension
d = {v: v ** 2 for v in range(10)}
print d
# {0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64, 9: 81}
# ===
# List indexes / List enumeration
l = ['0', '1', '2', '3', '4']
for i, v in enumerate(l):
print 'index: {0} val: {1}'.format(i, v)
# index: 0 val: 0
# index: 1 val: 1
# index: 2 val: 2
# index: 3 val: 3
# index: 4 val: 4
# ===
# Set operations
s = set('abracadabra')
t = set('simsalabim')
print s | t # Union
print s & t # Intersection
print s - t # Diff
# set(['a', 'c', 'b', 'd', 'i', 'm', 'l', 's', 'r'])
# set(['a', 'b'])
# set(['c', 'r', 'd'])
# ===
# List operations
l = [str(i) for i in range(10)]
print ''.join(l)
print list(''.join(l))
# 0123456789
# ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']
# ===
# Lambda Dict
lambda_dict = {
'lambda1': lambda x, y: x ** y,
'lambda2': lambda x: x ** 2,
'lambda3': lambda x: x ** 3
}
print lambda_dict['lambda1'](3, 4), lambda_dict['lambda2'](4)
# 81 16
# ===
# Setter, Getters
class Person(object):
def __init__(self, FirstName=None, LastName=None):
self.fn = FirstName
self.ln = LastName
@property
def FirstName(self):
return self.fn
@FirstName.setter
def FirstName(self, value=None):
self.fn = value
@property
def LastName(self):
return self.ln
@LastName.setter
def LastName(self, value=None):
self.ln = value
p1 = Person('Sponge', 'Bob')
print p1.FirstName, p1.LastName
# Sponge Bob
# ===
# Args, Key-word args
def args_demo(*args, **kwargs):
print type(args), type(kwargs)
for i in args:
print i
for k, v in kwargs.iteritems():
print k, v
args_demo(1, 2, 3, a='6', b='7', c='8')
# <type 'tuple'> <type 'dict'>
# 1
# 2
# 3
# a 6
# c 8
# b 7
# ===
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment