Solved

Python generators and a retrieve method

Posted on 2013-01-26
1
663 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
ID: 38824050
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

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
merging 2 mysql databases with java 7 58
Need To Find FireFox Binary Path For Python Selenium On Windows 7 15 434
How To Loop - Python 19 79
Python variable _ manually assigned 9 63
"The time has come," the Walrus said, "To talk of many things: Of sets--and lists--and dictionaries-- Of variable kinks-- And why you see it changing not-- And why so strange are strings." This part describes how variables and references (see …
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 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…
Learn the basics of while and for loops in Python.  while loops are used for testing while, or until, a condition is met: The structure of a while loop is as follows:     while <condition>:         do something         repeate: The break statement m…

912 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

20 Experts available now in Live!

Get 1:1 Help Now