Skip to content

Instantly share code, notes, and snippets.

@Alphare
Last active May 3, 2017 13:17
Show Gist options
  • Save Alphare/fc624796ddba7847e7e75b3422fba0d8 to your computer and use it in GitHub Desktop.
Save Alphare/fc624796ddba7847e7e75b3422fba0d8 to your computer and use it in GitHub Desktop.
Horrible way of mixing itemgetter and attrgetter that I used once
"""
Of course, this is not real code apart from the core functionality
"""
from __future__ import unicode_literals
from functools import reduce as functools_reduce
from operator import attrgetter, itemgetter
class DummyItem:
def __init__(self):
self.other_item = {'title': "whatever, it works"}
def __str__(self):
return "<other_item title='{}'/>".format(self.other_item['title'])
class DummyResponse:
def __init__(self):
self.item = DummyItem()
def __str__(self):
return "<item>\n\t{}\n</item>".format(self.item)
def compose(*functions):
return functools_reduce(lambda f, g: lambda x: f(g(x)), functions, lambda x: x)
data_checkers = [
{
"func": lambda x: x.startswith('whatever'),
"tag": 'item.other_item',
'attribute': 'title',
},
]
response = DummyResponse()
print(response)
for checker in data_checkers:
itemattrgetter = compose(
itemgetter(checker['attribute']),
attrgetter(checker['tag'])
)
assert checker['func'](itemattrgetter(response))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment