◐ Shell
clean mode source ↗

Message 83322 - Python tracker

This is the implementation of codecs.Streamwriter.writelines for all 
Python versions that I've checked:

    def writelines(self, list):

        """ Writes the concatenated list of strings to the stream
            using .write().
        """
        self.write(''.join(list))

This may be a problem if the 'list' parameter is a generator. The 
generator may be returning millions of values, which the join will 
concatenate in memory. It can surprise the programmer with large 
memory use. I think join should only be used when you know the size of 
your input, and this method does not know this. I think the safe 
implementation of this method would be:

    def writelines(self, list):

        """ Writes the concatenated list of strings to the stream
            using .write().
        """
        write = self.write
        for value in list:
            write(value)

If a caller knows that it's input list would use a reasonable amount 
of memory, it can get the same functionality as before by doing 
stream.write(''.join(list)).