Hacker News new | past | comments | ask | show | jobs | submit login

But that's good. Because a string just needs to know aboit interable to perform that operation whereas every iterable would need to implement it's own join if you had it the other way around.



It may be necessary in python, but in general, a language could allow you to define a join method on the iterable superclasss/trait/interface that iterates over the elements, converting each to a string, and inserting the separator between each of them.

For example, scala has Iterable#mkstring (https://docs.scala-lang.org/overviews/collections-2.13/trait...)


Yet Ruby and JS manage to do it somehow. To me it seems natural that join should be a method on the iterable, and I always have to pause to remember Python is different.


How does that work? Don’t you have to effectively convert your general iterable to an array and then join on that? Array.from(iterable).join(…)?


I don't think it should be a method at all. It's just a function: join(iterable, separator). It can also be implemented with reduce naturally: `reduce(lambda x, y: x + separator + y, iterable)`.


Reduce sounds like a really slow way to do string building


Oh yeah, it's horrendous, my point was just that it's functionally equivalent and makes more sense as a function than a method on either object. You can actually call it like this if you want, though: `str.join(separator, iterable)`.


The way it's managed in JS, digging the function out of the prototype to apply it, can be done in Python as well. But unlike JS you won't normally have to, thanks to the method not being defined only on one specific type of iterable.

JS:

  Array.prototype.join.call(["one", "two", "three"], "|")
Python:

  str.join("|", ["one", "two", "three"])


> Yet Ruby and JS manage to do it somehow.

Ruby does it by having a mixin (Enumerable) that anything meeting a basic contract (roughly equivalent to the Python iterable protocol) can include to get an enormous block of functionality; Python doesn’t have (or at least idiomatically use as freely; ISTR that there is a way to do it) mixins like Ruby does.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: