Sharing: File Reader Generator with & w/o Policy

Steven D'Aprano steve+comp.lang.python at pearwood.info
Sun Mar 16 06:36:28 EDT 2014


On Sat, 15 Mar 2014 23:47:30 -0500, Mark H Harris wrote:

> The other thing I'm tempted to do is to find names (even new names) that
> read like English closely (whatever I mean by that) so that there is no
> question about what is going on to a non expert.
> 
> for line in getnumline(file):
>        {whatever}

I'm not an expert on your code, and I have very little idea what that is 
supposed to do. Judging by the name "getnumline", my first guess is that 
the function takes a line number n, and it will return the nth line of 
some source:

getnumline(source, 5)
=> returns the 5th line from source

But that's not how you use it. You pass it a "file". Is that a file 
object, or a file name? My guess is that it would be a file object, since 
if you wanted a file name you would have written getnumline(filename). Is 
that a file object that is open for reading or writing? I'd have to guess 
that it's open for reading, since you're (probably?) "getting" from the 
file rather than "putting".

So... something like this:

file = open("some thing")
for line in getnumline(file):
    ...

Presumably it iterates over the lines of the file, but what it does with 
the lines is hard to say. If I had to guess, I'd say... maybe it's 
extracting the lines that start with a line number? Something like this 
perhaps?

def getnumline(file_object):
    count = 0  # Or start at 1?
    while True:
        line = file_object.readline()
        if line == '':
            break
        if line.startswith(str(count)):
            yield line
        count += 1

But this is only a guess, based on the assumption that while the function 
name is misleading, it's not *entirely* misleading. I'm puzzled why the 
function claims to do something with "line" singular, when you're 
obviously using it to iterate over lines plural.

Contrast that with an example from the Python built-ins: enumerate. What 
you get is exactly what it says on the tin: the function is called 
enumerate, and enumerate is what it does:


enumerate
    v 1: specify individually; "She enumerated the many obstacles
         she had encountered"; "The doctor recited the list of
         possible side effects of the drug" [syn: enumerate,
         recite, itemize, itemise]
    2: determine the number or amount of; "Can you count the books
       on your shelf?"; "Count your change" [syn: count, number,
       enumerate, numerate]



-- 
Steven D'Aprano
http://import-that.dreamwidth.org/



More information about the Python-list mailing list