Skip to content

Instantly share code, notes, and snippets.

@thomasballinger
Created July 12, 2013 14:25
Show Gist options
  • Save thomasballinger/5984855 to your computer and use it in GitHub Desktop.
Save thomasballinger/5984855 to your computer and use it in GitHub Desktop.
generator and decorator examples
def by_token(fileobj):
for line in fileobj:
for token in line.split():
yield token
import os
def open_file(func):
def newfunc(filename):
if os.path.exists(filename):
return func(open(filename))
else:
return func(open(raw_input('type another file')))
return newfunc
def hello(func):
print 'applying a decorator'
return func
@hello
@open_file
def dictreader(f):
lines = f.read().split('\n')
header = lines[0]
keys = header.split(',')
return [{k: v for k, v in zip(keys, line.split(','))}
for line in lines[1:] if line.strip()]
dictreader = open_file(dictreader)
@open_file
def text(f):
return f.read()
if __name__ == '__main__':
import pprint
pprint.pprint(dictreader('test.csv'))
pprint.pprint(text('test.csv'))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment