Created
July 12, 2013 14:25
-
-
Save thomasballinger/5984855 to your computer and use it in GitHub Desktop.
generator and decorator examples
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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