Wednesday, August 24, 2005

The spirit of the PEP

You hear a lot of people talking about the spirit of a law. It is a situation where a law is somewhat broad and requires interpretation.

Sometimes this happens in the programming world -- when it shouldn't. Yesterday I bugged a coworker into adding a feature to a console app of ours. The request was for an application to display a text status bar as it processed. It should have been along these lines:

[**** ] 45%

Asteriks give you a nice visual queue as to how complete the process is. The trailing percentage gives you an actual percentage of how much of the file has been processed. My coworker calls me today and yelps, "Eureka! I've discovered a use for generators."

A big question mark immediately floated over my head. Why would he use a generator? Generators are for yielding values. To yield the percentage of completion for our application, all he had to do was divide the number of bytes read by the number of bytes processed:

bytes_read / bytes_processed

Perturbed, I asked him how he used the generator. He responds, "I pass it the file object and it draws the status bar." I ask him if he knows what a generator should be used for. Apparently there is some confusion. I've never found a use for them myself. But, the classic example is for generating Fibonacci numbers :

def fib():
    a, b = 0, 1
    while 1:
        yield b
        a, b = b, a+b

The PEP even states that "the same kind of approach applies to many producer/consumer functions." After a bit of mental wrestling, he finally capitulated. He disclosed that he thought "it was cool" to do it that way. But really doing things the wrong way is never cool.

0 Comments:

Post a Comment

<< Home