[Python-ideas] textFromMap(seq , map=None , sep='' , ldelim='', rdelim='')

spir denis.spir at gmail.com
Mon Oct 25 15:49:32 CEST 2010


A recommended idiom to construct a text from bits -- usually when the bits themselves are constructed by mapping on a sequence -- is to store the intermediate results and then only join() them all at once. Since I discovered this idiom I find myself constantly use it, to the point of having a func doing that in my python toolkit:

def textFromMap(seq , map=None , sep='' , ldelim='',rdelim=''):
    if (map is None):
        return "%s%s%s" %(ldelim , sep.join(str(e) for e in seq) , rdelim)
        return "%s%s%s" %(ldelim , sep.join(str(map(e)) for e in seq) , rdelim)

Example use:

class LispList(list):
    def __repr__(self):
        return textFromMap(self , repr , ' ' , '(',')')
print LispList([1, 2, 3])   # --> (1 2 3)

Is there any similar routine in Python? If yes, please inform me off list and excuse the noise. Else, I wonder whether such a routine would be useful as builtin, precisely since it is a common and recommended idiom. The issues with not having it, according to me, are that the expression is somewhat complicated and, more importantly, hardly tells the reader what it means & does -- even when "unfolded" into 2 or more lines of code:

    elements = (map(e) for e in seq)
    elementTexts = (str(e) for e in elements)
    content = sep.join(elementTexts)
    text = "%s%s%s" %(ldelim , content , rdelim)

There are 2 discussable choices in the func above:
* Unlike join(), it converts to str automagically.
* It takes optional delimiter parameters which complicate the interface (but are really handy for my common use cases :-)
Also, the map parameter is optional in case there is no mapping at all, which is more common if the func "string-ifies" itself.

If ever you find this proposal sensible, then what should be the routine's name?
And where to integrate it in the language? I think there are at least 3 options:
1. A simple func                textFromMap(seq, ...)
2. A static method of str       str.fromMap(seq, ...)
3. A method for iterables (1)   seq.textFromMap(...)
(I personly find the latter more correct semantically (2).)

What do you think?


(1) I don't know exactly what should be the top class, if any.
(2) I think the same about join: should be "seq.join(sep)" since for me the object on which the method applies is seq, not sep.
-- -- -- -- -- -- --
vit esse estrany ☣


More information about the Python-ideas mailing list