3 ms·
Nice post overall, but I take issue with a couple of the examples. First, the YoutubeSearch class has no reason to be a class. It wants to be a function: d
by pjscott 14y ago
Nice post overall, but I take issue with a couple of the examples. First, the YoutubeSearch class has no reason to be a class. It wants to be a function:
def youtube_search(term):
url = 'https://gdata.youtube.com/feeds/api/videos'
params = {'q': term, 'alt': 'json', 'orderby': 'relevance', 'v': '2'}
r = requests.get(url, params=params)
r.raise_for_status() # 4xx and 5xx replies raise exception
for video in r.json.get('feed').get('entry'):
yield {
'title': video.get('title').get('$t'),
'url': video.get('link')[0].get('href'),
}
The ExpressiveList's __sub__() method, as written in the article, requires O(n*k) time to remove k things from a list of length n. By using a set of things to remove, we can get that down to O(n+k):
class ExpressiveList(list):
def __sub__(self, other):
if isinstance(other, list):
other_set = set(other)
return ExpressiveList(x for x in self if x not in other_set)
else:
return ExpressiveList(x for x in self if x != other)
- jspthrowaway2 14y agoThe primary reason to make YoutubeSearch a class is, in the future, implementing searching other video sites and taking advantage of inheritance in the implementation. That isn't demonstrated here, but the plumbing of "doing a request", "providing an iterator" and such could be promoted to the base class and subclasses are only responsible for knowing their domain.
- wahnfrieden 14y agoYAGNI and besides you can still provide two layers of access, one being convenience functions on top of the class implementation.
- icebraining 14y agoWhen you actually want to implement those other sites, you can replace the function by a class with a __call__ method.
- hcarvalhoalves 14y agoThere's no practical difference between a method and a class in this case.
- mercurial 14y agoHaving YoutubeSearch be a class doesn't really bother me, especially since the point of the post was to demonstrate the use of __ methods, and you can't do that if you're using a method instead. However, I discourage promoting inheritance (except in the guise of mixin, and even then...) as a way to factorize common functionalities. Composition is usually much better suited.
- cobbal 14y agoWhat's worse about the __sub__ method is that it will work in unpredictable ways, for instance >>> ExpressiveList(item, [2], [3]) - item will either be [[2], [3]] if item isn't a list, or something different if item is a list. This goes against the "Explicit is better than implicit" philosophy of python, and can cause all sorts of headaches later.