More questions on Python strings

Peter Otten __peter__ at web.de
Mon Sep 1 01:03:47 CEST 2014


MRAB wrote:

> On 2014-08-31 18:37, Dennis E. Evans wrote:
>>
>>    Hi
>>
>> I have a function that reads some meta data from a database and builds a
>> default order by and where clause for a table.

>>    Is the a way to build the strings with out using the intermediate
>>    list?
>>
>>    the end result needs to look like this,
>>
>>    self.OrderBy = "tableAlias.ColumnOne, tableAlias.ColumnTwo, ..."
>>
>>    self.WhereClause = "(tableAlias.ColumnOne = ?) and
>>    (tableAlias.ColumnTwo = ?) and ..."
>>
> You could use a generator comprehension:
> 
>         self.PkOrderBy =
> CommaSpace.join(defaultColumn.format(Ali=self.alias,
> ColLabel=oneRow[KeyLabelPos]) for oneRow in rows)
> 
> Does that make the code clearer? I don't think so. Or faster? Not
> enough to be noticeable.
> 
> Incidentally, there's no need to treat the single-row case specially:
> 
>  >>> ' and '.join(['first', 'second', 'third'])
> 'first and second and third'
>  >>> ' and '.join(['first', 'second'])
> 'first and second'
>  >>> ' and '.join(['first'])
> 'first'

The same goes for the no-rows case:

>>> " and ".join([])
''

You might also introduce a helper function to reduce code redundancy:

    def ReadPkColumns(self) :
        rows = self.cursor.fetchall()

        def build_clause(sep, template):
            return sep.join(
                template.format(Ali=self.alias, ColLabel=row[KeyLabelPos])
                for row in rows)

        self.PkOrderBy = build_clause(CommaSpace, defaultColumn)
        self.PkWhereClause = build_clause(andConjunction,
                                         defaultColumnParaMarker)

General observations: don't microoptimize (always col = [] instead of 
col.clear()) and don't comment your code to death ;)
Also: CommaSpace instead of the literal ", " string? When you bind it to 
another value like

CommaSpace = ";\t"

you will also have to change the name to SemicolonTabulator anyway.






More information about the Python-list mailing list