quasi-literal strawman

Andy Chu andy at chubot.org
Wed Dec 16 00:38:24 PST 2009


>> If you haven't yet read http://www.python.org/dev/peps/pep-3101/ (Advanced String Formatting) I suggest you do - its well worth a read and feels like a possible very javascripty solution.
>
> I have not read it.  Thanks for the link.  It has a good summary of
> alternate syntaxes and establishes a point partway between positional
> and inline syntax.  It does include a bunch of format specifiers that
> I think incompatible with DSL schemes.

I also like Python 3's string formatting design.  But it makes me
wonder -- how much of the quasi-literal proposal can be done in a
library?  I think basically all of string formatting could be
implemented as a library in Python 2 -- you just need to implement
your own .format() method on strings.

JSON Template was explicitly designed to be "upwardly compatible" with
Python 3k string formatting: http://code.google.com/p/json-template/

Here's how you would embed HTML:

'{name|html}: <a href="{url|html-attr-value}">{anchor|html}</a>'

where html escapes <>& and html-attr-value escapes <>&".

You can set a default formatter for security:

t = jsontemplate.Template('{name}: <a
href="{url|html-attr-value}">{anchor}</a>', default_formatter='html')

It's compiled into alternating literal strings and substitution nodes.

I like the idea of "enabling DSLs", but I feel like this proposal is a
DSL itself, rather than enabling them, since it has a fairly
particular syntax, and you have defined the parse tree very
specifically.

Another Python analogy is that they chose not to embed regex's in the
language, unlike JavaScript/Perl/Ruby.  Instead there is a very
minimal syntactic accomodation -- raw strings which don't have
backslash escaping.  The Go language takes this same approach with
backticks I believe (e.g. `\s+` and not "\\s+").

I do think JavaScript really needs better string interpolation than
"foo " + var + " bar", which unfortunately a common idiom.  I think
that perhaps all that would be necessary is to have a .format() method
on strings, like Python.  Python switched from the operator % to a
simple method.

Andy


More information about the es-discuss mailing list