Solved

Python generators and a retrieve method

Posted on 2013-01-26
1
677 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

Announcing the Most Valuable Experts of 2016

MVEs are more concerned with the satisfaction of those they help than with the considerable points they can earn. They are the types of people you feel privileged to call colleagues. Join us in honoring this amazing group of Experts.

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
Updating urls.py doesn't work 4 86
Installing Flask app on IIS7 10 451
Merge lists using index in Python 1 113
Python Encoding Problem \u2013 4 135
The really strange introduction Once upon a time there were individuals who intentionally put the grass seeds to the soil with anticipation of solving their nutrition problems. Or they maybe only played with seeds and noticed what happened... Som…
Dictionaries contain key:value pairs. Which means a collection of tuples with an attribute name and an assigned value to it. The semicolon present in between each key and values and attribute with values are delimited with a comma.  In python we can…
Learn the basics of if, else, and elif statements in Python 2.7. Use "if" statements to test a specified condition.: The structure of an if statement is as follows: (CODE) Use "else" statements to allow the execution of an alternative, if the …
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…

730 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