Neosynapse is proud to offer its second open-source "building block"
package, istring. The Neosynapse istring package provides Python 2.2 support
for interpolated strings. See the following items from the README, and
check out the README for complete details. Neosynapse's istring package
is available under the LGPL-like Neosynapse Community License.
Update! Version 1.0.1 of istring has been released. The new version fixes
several bugs. It also uses distutils for installation.
In addition, a mailing list for istring announcements has been created.
Major releases will still be announced on python-list (as well as istring-announce),
but minor updates and bugfix releases will be announced on the istring
announcements list only. This list is expected to be very low-traffic.
What is istring?
istring is an interpolated string class, which means you can substitute
variables into a string, like this:
>>> j = 3
>>> s = istring("j is $j")
>>> s
'j is 3'
The istring class requires many features from Python 2.2, so you must
install Python 2.2 to use this class. All istring objects are derived
from full-fledged Python string objects, so you can do anything to an
istring that you can do to a regular string, including take slices and
use as a pattern in a regular expression.
Although the istring class was created with SQL in mind, it may be used
for many purposes. istrings fully support interpolation of dictionary
values, list values, and return values from functions or class methods.
It is intelligent about variable replacement, so for example it is not
confused by:
>>> s = istring("$k=3")
i.e. it does not try to intepret "=3" as part of the variable.
Why would I want to interpolate variables when I could use %s notation?
Ask yourself which query is clearer:
(1) db.query("""SELECT foo, bar
FROM %s
WHERE rsrc_id = %s
AND name = '%s'""" % (table, rsrc_id, name))
Or:
(2) qry = istring("""SELECT foo, bar
FROM $table
WHERE rsrc_id = $rsrc_id
AND name = $.name""")
db.query(qry)
To make this even cleaner, we could write a function that took a regular
raw string with istring interpolation, then made an istring of it and
submitted the query, like this:
(3) db.iquery("""SELECT foo, bar
FROM $table
WHERE rsrc_id = $rsrc_id
AND name = $.name""")
To me, there's no question that (3) is the easiest to read. However,
since istring descends from the regular Python string class, you can use
% notation intermixed with istring interpolation:
>>> m = "abc"
>>> n = "def"
>>> test_dict = {'foo': 'bar', 'yak': 'lmnop'}
>>> istring("value=%(foo)s$m,%(yak)s$n") % test_dict
"value=barabc,lmnopdef"
Where can I get istring?
Here: istring101.tar.gz
|