Solved

Python generators and a retrieve method

Posted on 2013-01-26
1
685 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
1 Comment
 
LVL 29

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

On Demand Webinar: Networking for the Cloud Era

Ready to improve network connectivity? Watch this webinar to learn how SD-WANs and a one-click instant connect tool can boost provisions, deployment, and management of your cloud connection.

Question has a verified solution.

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

This article will show the steps for installing Python on Ubuntu Operating System. I have created a virtual machine with Ubuntu Operating system 8.10 and this installing process also works with upgraded version of Ubuntu OS. For installing Py…
Flask is a microframework for Python based on Werkzeug and Jinja 2. This requires you to have a good understanding of Python 2.7. Lets install Flask! To install Flask you can use a python repository for libraries tool called pip. Download this f…
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 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…

728 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