Search code examples
pythonjoinmagic-methods

Is any magic method called on an object in a list during join()?


Joining a list containing an object - is there any magic method I could set to convert the object to a string before join fails?

', '.join([…, Obj, …])

I tried __str__ and __repr__ but neither did work


Solution

  • Nope, there's no join hook (although I've wanted this feature as well). Commonly you'll see:

    ', '.join(str(x) for x in iterable)
    

    or (almost) equivalently:

    ', '.join(map(str,iterable))
    ', '.join([str(x) for x in iterable])
    

    (Note that all of the above are equivalent in terms of memory usage when using CPython as str.join implicitly takes your generator and turns it into a tuple anyway.)