[Python-ideas] Statements vs Expressions... why?

Cliff Wells cliff at develix.com
Wed Sep 10 23:54:44 CEST 2008

On Wed, 2008-09-10 at 11:43 -0700, Cliff Wells wrote:

> Specifically, I'd like to see things like "if" statements, "for" loops,
> etc, become expressions.  This would not preclude them from being used
> as if they were statements (an expression can stand alone on a line of
> Python code), but would add a lot of expressiveness to the language as
> well as make Python more viable for creating DSLs.

Because I know that the question "what's your use case" will inevitably
be forwarded, I will explain the exact use case that has driven me to
distraction over this limitation.

I developed and maintain a template engine written in Python:


As you can see from the example on the main page, Breve is written as an
internal DSL (that is, it compiles directly to Python bytecode... Breve
templates *are* Python).  This means that any limitation in Python is
inherently a limitation in Breve.

There were several design decisions to be made when designing Breve, the
first and foremost being "will Breve templates be full-blown Python
programs or will they be limited to expressions?".  I chose the latter
for a few reasons:

1) Python expressions map more directly to the generated XML/HTML
output.  In other words, a Breve template has the same structure (if not
syntax) as the desired result.
2) It would have required additional syntax within the template to allow
for all of Python to be supported. 

Overall, I'm happy with my choice, but it forces some mental twister
when trying to do particular operations in Breve, notably
presentation-logic and looping.   A loop must be presented as a list
comprehension.  "If" logic must be done using either 2.5's ternary if
operator or using short-circuit logical operations, i.e. "test(value)
and (this)".  At one point I actually implemented custom tags for doing
logical operations, but due to the inability to provide
short-circuiting, they were less than satisfactory.

This isn't fatal to Breve (albeit annoying), but it made me painfully
aware of this self-imposed limitation in Python.  It also made me wonder
what other concepts this limitation has prevented me from grokking over
this last decade.  It's generally accepted that a language constrains
not only the solutions to a problem, but also the *possible* solutions
that a programmer will see.  This is as much of a concern to me as any
practical concerns today. 


More information about the Python-ideas mailing list