Monday, September 24, 2012

What is lazy what is eager


http://stackoverflow.com/questions/11619464/seeking-guidelines-for-lazy-izing-python-data


The basic idea of "lazy" code is that the code does not get data until it needs the data.
For example, suppose I am writing a function to copy a text file. It would not be lazy to read the entire file into memory, then write the entire file. It also would not be lazy to use the .readlines() method to build a list out of all the input lines. But it would be lazy to read one line at a time and then write each line after reading.
# non-lazy
with open(input_fname) as in_f, open(output_fname, "w") as out_f:
    bytes = in_f.read()
    out_f.write(bytes)
# also non-lazy
with open(input_fname) as in_f, open(output_fname, "w") as out_f:
    lines = in_f.readlines()
    for line in lines:
        out_f.write(line)
# lazy
with open(input_fname) as in_f, open(output_fname, "w") as out_f:
    for line in in_f:  # only gets one line at a time
        out_f.write(line) # write each line as we get it
To help make your code lazy, Python lets you use "generators". Functions written using the yieldstatement are generators. For your database example, you could write a generator that would yield up one row at a time from the database, and then you could write code like this:
def db_rows(database_name):
    # code to open the database goes here
    # write a loop that reads rows
        # inside the loop, use yield on each row
        yield row
    # code to close the database goes here
for row in db_rows(database_name):
    # do something with the row







No comments:

Post a Comment