[Python-3000] interpolated strings
Antoine
solipsis at pitrou.net
Wed Dec 6 12:50:37 CET 2006
> On Wed, 6 Dec 2006, Ka-Ping Yee wrote:
> and "%" is overloadable on the basis that the return type is determined
> to be compatible with "some_type_that_signals_sql_interpolation". Those
> are some mighty big "IF"s though, and you could still concoct cases
> where things would break :-)
Or perhaps simpler, a new kind of string literal would construct an
Interpolation object:
s = i"some string here with {variable} in it"
equivalent to:
s = Interpolation("some string here with {variable} in it",
{"variable": <current value of "variable">})
The Interpolation object captures the format string, as well as a dict of
the needed variables from the current locals and globals (here, the
"variable"). But it does not render the interpolated string immediately,
just stores the values for future use.
The __str__ method on the Interpolation object would do the "obvious"
thing, i.e. interpolate without any quoting. However, nothing stops a more
demanding object from doing its own interpolation instead of blindly
calling __str__. For example, in:
d = SqlDriver(...)
s = i"select password from {user}"
r = d.query(s)
d.query() would automatically quote all variables before interpolating.
The Interpolation object could provide convenience methods to make this
trivial for library implementers, e.g. a render(quote_function=None)
method.
So d.query() could look like the following:
def query(self, s):
if hasattr(s, "render"):
s = s.render(quote_function=self.sql_quote_value)
else:
s = str(s)
# do stuff
More information about the Python-3000
mailing list