[Python-ideas] Symbolic expressions

Greg greg.ewing at canterbury.ac.nz
Sat Jan 14 21:18:37 CET 2012

Oleg Broytman wrote:

> Symbolic algebra is a widely-deployed technique in Python world. It
> is popular, e.g., in object-relational mappers. IMHO Python is powerful
> enough in that area, there is no need to change the language.

The existing techniques for this get a bit awkward at times,
though, for example when you want boolean operations, since
'and' etc. can't be overridden.

My Overloadable Boolean Operators PEP was one attempt to
address this problem, but it hasn't met with a very enthusiastic

Recently I've been working on another approach using that
I've been calling "deferred expressions" (although I'll probably
change that name because "deferred" seems to have taken on a
different meaning already).

The idea is that you write something like this (sorry about the
ugly syntax, I haven't thought of anything better yet):

    e = <(a + b * c)>

This gives you something that behaves in one respect like a
parameterless lambda -- you can evaluate it, and any free
variables are interpreted in their original environment.

However, its internal structure is effectively an AST that
you can pick apart and process however you want, including
selectively evaluating sub-expressions and building up new

Currently they're not generative the way the OP wants, i.e.
you can't do 'e1 + e2' and get a new deferred expression, but
that could be arranged, and would provide a nice way of
building new expressions. The only problem would be attribute
access, since they currently have attributes modelled after
those of the corresponding AST nodes, whereas under a
generative regime, 'e.a' ought to return a new expression node
representing the access of attribute 'a'.

I have about 90% of this implemented. I'll make a release
as soon as I have something fit for public consumption.


More information about the Python-ideas mailing list