Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #77369

Re: More questions on Python strings

From Peter Otten <__peter__@web.de>
Subject Re: More questions on Python strings
Date 2014-09-01 01:03 +0200
Organization None
References <e008fcef-6d95-4123-a2e1-eeac5fd54ba3@googlegroups.com> <54036730.6010500@mrabarnett.plus.com>
Newsgroups comp.lang.python
Message-ID <mailman.13670.1409526247.18130.python-list@python.org> (permalink)

Show all headers | View raw


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.


Back to comp.lang.python | Previous | NextPrevious in thread | Find similar | Unroll thread


Thread

More questions on Python strings "Dennis E. Evans" <dennisearlevans@gmail.com> - 2014-08-31 10:37 -0700
  Re: More questions on Python strings MRAB <python@mrabarnett.plus.com> - 2014-08-31 19:19 +0100
  Re: More questions on Python strings Peter Otten <__peter__@web.de> - 2014-09-01 01:03 +0200

csiph-web