Python garbage collector/memory manager behaving strangely

Steven D'Aprano steve+comp.lang.python at pearwood.info
Mon Sep 17 07:47:47 EDT 2012


On Mon, 17 Sep 2012 06:46:55 -0400, Dave Angel wrote:

> On 09/16/2012 11:25 PM, alex23 wrote:
>>     def readlines(f):
>>         lines = []
>>         while "f is not empty":
>>             line = f.readline()
>>             if not line: break
>>             if len(line) > 2 and line[-2:] == '|\n':
>>                 lines.append(line)
>>                 yield ''.join(lines)
>>                 lines = []
>>             else:
>>                 lines.append(line)
> 
> There's a few changes I'd make:
> I'd change the name to something else, so as not to shadow the built-in,

Which built-in are you referring to? There is no readlines built-in.

py> readlines
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'readlines' is not defined


There is a file.readlines method, but that lives in a different namespace 
to the function readlines so there should be no confusion. At least not 
for a moderately experienced programmer, beginners can be confused by the 
littlest things sometimes.


> and to make it clear in caller's code that it's not the built-in one.
> I'd replace that compound if statement with
>       if line.endswith("|\n":
> I'd add a comment saying that partial lines at the end of file are
> ignored.

Or fix the generator so that it doesn't ignore partial lines, or raises 
an exception, whichever is more appropriate.



-- 
Steven



More information about the Python-list mailing list