Skip to content

Instantly share code, notes, and snippets.

@t9md
Created October 31, 2010 11:58
Show Gist options
  • Save t9md/656498 to your computer and use it in GitHub Desktop.
Save t9md/656498 to your computer and use it in GitHub Desktop.
python decorator example
#!/usr/bin/env python
# -*- coding: utf8 -*-
############################################
## Setup
############################################
# function which return newley created function
def gen_seq_transformer(f):
"""
Take trans function as argment
and return newley created function which
take sequence as argment.
and call function to each element in sequence
"""
def transformer(l):
new_seq = [ f(line) for line in l]
return new_seq
return transformer
# Target Data
org = ["abc", "def", "efg", "hij", "klm"]
############################################
print "== Primitive higher order function" + "=" * 10
# 1. apply uppper() to all element in sequence
upper_list = gen_seq_transformer(lambda x: x.upper())
print upper_list(org)
# 2. apply lower() to all element in sequence
lower_list = gen_seq_transformer(lambda x: x.lower())
print lower_list(ret)
# => ['abc', 'def', 'efg', 'hij', 'klm']
# 3. apply list() to all element in sequence
print gen_seq_transformer(list)(org)
# 4. apply len() to all element in sequence
print gen_seq_transformer(len)(org)
""" Result:
== Primitive higher order function==========
['ABC', 'DEF', 'EFG', 'HIJ', 'KLM']
['abc', 'def', 'efg', 'hij', 'klm']
[['a', 'b', 'c'], ['d', 'e', 'f'], ['e', 'f', 'g'], ['h', 'i', 'j'], ['k', 'l', 'm']]
[3, 3, 3, 3, 3]
"""
############################################
# Decorator Version
############################################
print "== Decorator Version " + "=" * 10
org = ["abc", "def", "efg", "hij", "klm"]
# 1. apply uppper() to all element in sequence
@gen_seq_transformer
def transform_upper(l): return l.upper()
print transform_upper(org)
# 2. apply lower() to all element in sequence
@gen_seq_transformer
def transform_lower(l): return l.lower()
print transform_lower(org)
# 3. apply list() to all element in sequence
@gen_seq_transformer
def transform_list(l): return list(l)
print transform_list(org)
# 4. apply len() to all element in sequence
@gen_seq_transformer
def transform_len(l): return len(l)
print transform_len(org)
""" Result:
== Decorator Version ==========
['ABC', 'DEF', 'EFG', 'HIJ', 'KLM']
['abc', 'def', 'efg', 'hij', 'klm']
[['a', 'b', 'c'], ['d', 'e', 'f'], ['e', 'f', 'g'], ['h', 'i', 'j'], ['k', 'l', 'm']]
[3, 3, 3, 3, 3]
"""
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment