3 ms·
So we have so if I was wrong in my original assumption that stuff has exactly one element, Python will shout at me before this will manifest itself as a hard-t
by statictype 16y ago
So we have
so if I was wrong in my original assumption that stuff has exactly one element, Python will shout at me before this will manifest itself as a hard-to-find bug someplace else in the program.
and then later on,
This method works even when stuff is a set or any other kind of collection. stuff[0] wouldn’t work on a set because set doesn’t support access by index number.
The second argument is basically in favor of duck-typing which is the pythonic way of writing code, ie, not caring about the actual object but only if it responds to the given message.
But what about the first argument? Couldn't you make the case that the pythonic way of handling it is to only care about if the object responds to __getitem__(0)?
Which idiom you use would depend entirely on context, wouldn't it?
- cool-RR 16y agoDuck-typing means you don't assume that the object is from a certain type; Instead you assume that it's got the interfaces you need. (Either `.__iter__()` or `.__getitem__(0)` in this case.) `.__iter__()` is a more general and common interface than `.__getitem__(0)`, so it's preferable to assume that the object implements the former rather than the latter. But sometimes you do want to assume stuff about your object. In this case we want to assume that the list has exactly one item, and we want our code to break immediately if it isn't true.
- masklinn 16y ago> But what about the first argument? Couldn't you make the case that the pythonic way of handling it is to only care about if the object responds to __getitem__(0)? Mmm no? Here, what he cares about is that it's a single-element collection, he doesn't just want the collection's first item. If he did, foo[0] would do a better job. So the object responding to __getitem__(0) is not a sufficient condition. In fact, it's entirely wrong as sets do _not_ implement __getitem__. Worse, __getitem__(0) does a very different thing than unpacking on a dict. Unpacking is more ducky than __getitem__ for this case, because it expresses the following: the right-hand is a single-element iterable. Any iterable will work as long as it only has a single item, it doesn't have to be a sequence, a mapping, or even a collection (generators or callable_iterators will work just as well)
- digitallogic 16y agoDepends on which is more important. If it's an egregious error for there to be more than one element then I'd prefer the unpacking solution. However if ordering is/was involved at some point a set would indicate a possible bug (since they're unordered) so I might lean towards indexing. They are both decent ideas, not hard fast rules. Let your context be your guide.