[Baypiggies] Discussion for newbies/beginner night talks
Paul McNett
p at ulmcnett.com
Sat Feb 10 02:05:17 CET 2007
Dennis Reinhardt wrote:
> At 03:57 PM 2/9/2007, Shannon -jj Behrens wrote:
>> On 2/9/07, Dennis Reinhardt <DennisR at dair.com> wrote:
>>> This is an optimization and as such may not be the first approach to
>>> consider. All of the code samples I showed used string appends such as
>>>
>>> str = ""
>>> str += "string 1"
>>> str + "string 2"
>>> ...
>> #) Use triple quoted strings, and use buffers.
>
> Triple quoted strings are often a poorer solution.
>
> 1) to avoid breaking up the indentation structure, triple quoted
> strings must either have lots of extra white space or must be
> defined globally. If globally, subroutine level parameter
> substitution is awkward.
I respectfully disagree. Take this example:
class MyBizobj(...):
def getCustomerInfo(self, cust_id):
sql = """
select customers.name as name,
sum(invoices.amount) as amount_total,
blah as blah
from customers
left join invoices
on invoices.cust_id = customers.id
where customers.id = ?"""
self.cur.execute(sql, (cust_id,))
On one level, it is kind of ugly because I don't indent the lines to
match the indentation of the code. On the other hand, it is easy to follow.
> 2) Parameter substitution is very awkward for long blocks of
> text.
Again, I disagree.
> A common idiom I run up against is defining html in which the user may have
> already entered a value. So, one might find:
>
> html += "<input type=text name=xyz value=%s>" % previous("xyz")
>
> and where it is understood that previous() reads the invoking URL for the
> xyz= parameter value.
>
> Doing this in a long triple string is ugly.
You should use named arguments in string formatting. Such as:
html += """
<input type="text" name="%(field_name)s" value="%(field_value)s">
""" % locals()
Ok ok, this example is kind of ugly too, but it seems better when you
actually have a block of html.
--
pkm ~ http://paulmcnett.com
More information about the Baypiggies
mailing list