[Python-Dev] Re: PEP 292, Simpler String Substitutions
Christian Tismer
tismer@tismer.com
Sat, 29 Jun 2002 17:48:00 +0200
Extended proposal at the end:
Paul Prescod wrote:
> Christian Tismer wrote:
>
>>...
>>
>>Are you sure you got what I meant?
>>I want to compile the variable references away at compile
>>time, resulting in an ordinary format string.
>>This string is wraped by the runtime _(), and
>>the result is then interpolated with a dict.
>
>
> How can that be?
>
> Original expression:
>
> _($"$foo")
>
> Expands to:
>
> _("%(x1)s"%{"x1": foo})
>
> Standard Python order of operations will do the %-interpolation before
> the method call! You say that it could instead be
>
> _("%(x1)s")%{"x1": foo}
>
> But how would Python know to do that? "_" is just another function.
> There is nothing magical about it. What if the function was instead
> re.compile? In that case I would want to do the interpolation *before*
> the compilation, not after!
>
> Are you saying that the "_" function should be made special and
> recognized by the compiler?
My idea has evolved into the following:
Consider an interpolating object with the following
properties (sketched by a class here):
class Interpol:
def __init__(self, fmt, dic):
self.fmt = fmt
self.dic = dic
def __repr__(self):
return self.fmt % self.dic
Original expression:
_($"$foo")
Expands at compile time to:
_( Interpol("%(x1)s", {"x1": foo}) )
Having said that, it is now up to the function _()
to test whether its argument is an Interpol or not.
It can do something like that:
def _(arg):
...
if type(arg) is Interpol:
return _(arg.fmt) % arg.dic
# or, maybe cleaner, leaving the formatting action
# to the Interpol class:
def _(arg):
...
if isinstance(arg, Interpol):
return arg.__class__(_(arg.fmt), arg.dic)
# which then in turn will return the final string,
# if it is interrogated via str or repr.
ciao - chris
--
Christian Tismer :^) <mailto:tismer@tismer.com>
Mission Impossible 5oftware : Have a break! Take a ride on Python's
Johannes-Niemeyer-Weg 9a : *Starship* http://starship.python.net/
14109 Berlin : PGP key -> http://wwwkeys.pgp.net/
work +49 30 89 09 53 34 home +49 30 802 86 56 pager +49 173 24 18 776
PGP 0x57F3BF04 9064 F4E1 D754 C2FF 1619 305B C09C 5A3B 57F3 BF04
whom do you want to sponsor today? http://www.stackless.com/