Skip to content

Instantly share code, notes, and snippets.

@jjmerchante
Created November 16, 2017 11:12
Show Gist options
  • Save jjmerchante/dab193a925c889fac8910a246716cfa4 to your computer and use it in GitHub Desktop.
Save jjmerchante/dab193a925c889fac8910a246716cfa4 to your computer and use it in GitHub Desktop.
Some Python idioms

Python idioms

magic methods (about 100)

from os.path import join

class FileObject:
    '''Wrapper for file objects to gets closed on deletion.'''

    def __init__(self, filepath='~', filename='sample.txt'):
        # open a file filename in filepath in read and write mode
        self.file = open(join(filepath, filename), 'r+')

    def __del__(self):
        self.file.close()
        del self.file

decorators

def onexit(f):
    import atexit
    atexit.register(f)
    return f

@onexit
def func():
    ...

@classmethod

@staticmethod

class A(object):
    def foo(self,x):
        print "I am a method of A's instance :)"

    @classmethod
    def class_foo(cls,x):
        print "I am a class_method, I know about the class :)"

    @staticmethod
    def static_foo(x):
        print "I am a static_method, I don't know about the class :)"

@total_ordering

@total_ordering
class Student:
    def __eq__(self, other):
        return ((self.lastname.lower(), self.firstname.lower()) ==
                (other.lastname.lower(), other.firstname.lower()))
    def __lt__(self, other):
        return ((self.lastname.lower(), self.firstname.lower()) <
                (other.lastname.lower(), other.firstname.lower()))

if __name__ == '__main__'

def foo():
    print("I am foo")

if __name__ == "__main__":
    foo()

namedtuple

import collections
Person = collections.namedtuple('Person', 'name age gender')
bob = Person(name='Bob', age=30, gender='male')
print ('Representation:', bob)
print ('Field by name:', bob.name)

yield

# python3
def createGenerator():
    mylist = range(3)
    for i in mylist:
        yield i*i

with

with open("x.txt") as f:
    data = f.read()
    # do something with data

lambda functions

def adder(x):
    return lambda y: x + y
add5 = adder(5)
add5(1)

map

filter

reduce

items = [1, 2, 3, 4, 5, 6]
# map
squared = map(lambda x: x**2, items)
# filter
odds = filter(lambda x: x % 2, items)
# reduce
product = reduce((lambda x, y: x * y), items)

nested functions

def make_printer(msg):
    def printer():
        print (msg)
    return printer

printer = make_printer('Foo!')
printer()

finally

try:
    run_code1()
except TypeError:
    run_code2()
    return None   # The finally block is run before the method returns
finally:
    other_code()

List comprehension

Dict comprehension

Generator expressions

list_comp = [x * 2 for x in range(10)]
gen_expr = (x * 2 for x in range(10**20)) # xrange in python2
dict_comp = {x:chr(65+x) for x in range(1, 11)}

deque

defaultdict

OrderedDict

from collections import deque, defaultdict, OrderedDict

d = deque("bc")
d.append(d.pop())
d.appendleft(d.popleft())

ddict = defauldict(int)
for num in [1, 2, 4, 5, 3, 1, 2, 4, 5, 1]:
    ddict[num] += 1

odict = OrderedDict(sorted(ddict.items(), key=lambda t: t[1]))

Some itertools

zip

x = [1, 2, 3]
y = [4, 5, 6]
zipped = zip(x, y)

izip

izip_longest

list(izip('abc', [1, 2, 3, 4, 5]))
list(izip_longest('abc', [1, 2, 3, 4, 5]), fillvalue='-')

groupby

things = [("animal", "bear"), ("animal", "duck"), ("plant", "cactus"), ("vehicle", "speed boat"), ("vehicle", "school bus")]
groupby(things, lambda x: x[0])
  • imap
  • startmap
  • tee
  • partial ...
  • Calling a function with an arguments with the equal operator
  • assert
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment