Skip to content

Instantly share code, notes, and snippets.

@justinfay
Created June 20, 2013 09:54
Show Gist options
  • Save justinfay/5821587 to your computer and use it in GitHub Desktop.
Save justinfay/5821587 to your computer and use it in GitHub Desktop.
stupidly unpythonic methodcaller example
>>> from operator import methodcaller
>>> from random import randint
>>> class Foo(object):
... def __init__(self):
... self.number = randint(0, 10)
... def get_number(self):
... return self.number
...
>>> lfoos = [Foo() for i in xrange(10)]
>>> for foo in lfoos:
... print foo.number
...
4
5
9
5
10
10
0
3
0
6
>>> f = methodcaller('get_number')
>>> for foo in sorted(lfoos, key=lambda x: f(x)):
... print foo.number
...
0
0
3
4
5
5
6
9
10
10
>>>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment