3 ms·
I don't consider the sort example to be a quirk at all, though some of the other examples are reasonable. It's more a definition of what methods are supposed to
by barik 13y ago
I don't consider the sort example to be a quirk at all, though some of the other examples are reasonable. It's more a definition of what methods are supposed to do in the first place: a behavior that is applied on the instance of the object. Unless you're doing functional programming (or implementing certain specialized design patterns), you wouldn't expect dog.move() to return a new dog, so why should list.sort() return a new list?
- CognitiveLens 13y agoI generally agree with you but I think the recommendation would be that list.sort() should return the original list in its new, sorted state, not a new list.
- jofer 13y agoIt's just a coding convention in python. All in-place operations in python are supposed to return None, as a way of explicitly signaling that the operation was done on the existing object. It's not always followed outside the standard library, but it's very rare to run across an exception. It's counter-intuitive at first, especially in this case, but it is consistent.
- to3m 13y agoI always figured it was because "sort" is a verb. Over time I've come to feel that functions named with a verb phrase ought to be procedure-like, in that they have side effects and return either nothing (which in python means None) or some kind of error indicator (and in python you'd generally use exceptions instead). There are exceptions (e.g., the "get" prefix, used for getters, which tend to return values and have no side-effects), and, as with any rule of thumb, better to break it than create something ugly. But as rules go, I've found this one a pretty useful one to stick to.
- manojlds 13y agoI think this is where Ruby shines with the ! to indicate destructive.
- petercooper 13y agoIt would be, if only it were true. Consider Array#delete_if or Array#pop, for example, although there are many others too. Matz has written about this - https://www.ruby-forum.com/topic/176830#773946 https://www.ruby-forum.com/topic/176830#773946 - and said "The bang (!) does not mean "destructive" nor lack of it mean non destructive either. The bang sign means "the bang version is more dangerous than its non bang counterpart; handle with care". This is one of the most commonly misunderstood things about Ruby in my experience (enough so that some library developers do apply a ! == destructive naming system) and would certainly make an equivalent "Ruby quirks" list IMHO! :-)