Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generator instead of list comprehension? And where else can I improve my class?

I'm rather new to Python. Lately I was looking into the python's concept of classes. Well, for a couple of scripts I wrote I thought it would be handy to define a class which puts together a SQL-statement (in ArcGis dialect). Nothing fancy really. Here is what I came up with. I'm asking two things: first, general flaws? Suggestions for improvement? Secondly, I'm a little stuck with the code of the last function def constructor. Actually I want to return the tuple from the dictionary and not a list. But the list comprehension is nice. So what about a generator? I can't figure exactly out how to do that...

class ArcSql:
    type_book = {'str':("'","'"), 'int':("", "")}
    format_book = dict(shp=("'","'"), GDB=("[","]"))

    def __init__(self,colom_name, values_list, value_type = 'str', arc_format ='shp'):
        self.colom = colom_name
        self.values = values_list
        self.valtype = self.constructor(type_book, value_type)
        self.aformat = self.constructor(format_book, arc_format)
        self.colom_formated = str(self.aformat[0][0]) + self.colom + str(self.aformat[0][1])

    def statement(self):
        temp_state = []
        connector = "'OR' "
        count_values = len(self.values)
        if count_values == 0:
            return("error, not enough values...")
        else:
            for v in self.values:
                x = self.colom_formated + " = " + str(self.valtype[0][0]) + v + str(self.valtype[0][1]) + ' ' + connector
                temp_state.append(str(x))
        state = "".join(temp_state)[:-5]              
        return(str(state))

    def constructor(self, book, book_key):
        return([v for k,v in book.iteritems() if k==book_key])
like image 983
LarsVegas Avatar asked Feb 21 '23 07:02

LarsVegas


1 Answers

Your first question should be better asked in the codereview site.

Regarding your second question, you could use a generator as follows:

def constructor(self, book, book_key):
    for k, v in book.iteritems():
        if k==book_Key:
            yield v

...

for value in obj.constructor(book ,book_key):
    # Do whatever you need with value

Anyway, my understanding is that you're going to get only one result from the list comprehension, in such a case:

def constructor(self, book, book_key):
    return next(v for k, v in book.iteritems() if k==book_key, None)

...

value = obj.constructor(book ,book_key)
if value is not None:
    # Do whatever you need with value

Where next is a built-in to return the next value of an iterator or the default value passed (None in this case) if the iterator is exhausted (if no default value is passed, an exception will be raised in that case).

like image 200
jcollado Avatar answered Mar 09 '23 00:03

jcollado