Solved

Python generators and a retrieve method

Posted on 2013-01-26
1
656 Views
Last Modified: 2013-02-25
I am trying to do the practice question below I have gone as far as I can but I am stuck, can someone point me in the right direction.... I am getting stick in making each data row a new object. Normally i would think I could just iterate over the rows, but that will only return last row. I am also having a problem getting the retrieve function to work right. I think I need a SELECT fectall() then iterate over it and return it somehow but that is where I am lost.

Question:

Modify the classFactory.py source code so that the DataRow class returned by the build_row function has another method:

   retrieve(self, curs, condition=None)

self is (as usual) the instance whose method is being called, curs is a database cursor on an existing database connection, and condition (if present) is a string of condition(s) which must be true of all received rows.

The retrieve method should be a generator, yielding successive rows of the result set until it is completely exhausted. Each row should be a new object of type DataRow.


     def build_row(table, cols):
         """Build a class that creates instances of specific rows"""
         class DataRow:
             """Generic data row class, specialized by surrounding function"""
             def __init__(self, data):
                 """Uses data and column names to inject attributes"""
                 assert len(data)==len(self.cols)
                 for colname, dat in zip(self.cols, data):
                     setattr(self, colname, dat)
             def __repr__(self):
                 return "{0}_record({1})".format(self.table, ", ".join(["   {0!r}".format(getattr(self,c))     for c in self.cols]))
   
   
    DataRow.table = table
    DataRow.cols = cols.split()
    return DataRow
0
Comment
Question by:afg797s
1 Comment
 
LVL 28

Accepted Solution

by:
pepr earned 500 total points
Comment Utility
Normally i would think I could just iterate over the rows, but that will only return last row. I am also having a problem getting the retrieve function to work right. I think I need a SELECT fectall() then iterate over it and return it somehow but that is where I am lost.

It seems you are almost there. Firstly, think about the separate problems separately. Only after solving the subproblems, put them together:

01. New method is just a method.

It just takes some arguments to be used in its body.

02. It will behave as a generator.

It usually means there is some loop (like iteration through the rows accessed by the cursor), and it generates one result in one loop cycle (here only when condition holds). Definitely, it uses the yield result command in the loop body. (This is your command "to return the result somehow" in your case.)

03. The method will be used (called) at the place where generators can be placed.

It usually means it will be placed at the end of the for loop (just before the colon).
For me, the design makes sense only when the self datarow content is to be used with the condition to decide, whether the current row should produce the newly created, yielded DataRow object (or not).
0

Featured Post

How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

Join & Write a Comment

Variable is a place holder or reserved memory locations to store any value. Which means whenever we create a variable, indirectly we are reserving some space in the memory. The interpreter assigns or allocates some space in the memory based on the d…
When we want to run, execute or repeat a statement multiple times, a loop is necessary. This article covers the two types of loops in Python: the while loop and the for loop.
Learn the basics of strings in Python: declaration, operations, indices, and slicing. Strings are declared with quotations; for example: s = "string": Strings are immutable.: Strings may be concatenated or multiplied using the addition and multiplic…
Learn the basics of modules and packages in Python. Every Python file is a module, ending in the suffix: .py: Modules are a collection of functions and variables.: Packages are a collection of modules.: Module functions and variables are accessed us…

762 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

6 Experts available now in Live!

Get 1:1 Help Now