[Zope] Evaluating python with my own variable bindings

Ross Boylan RossBoylan@stanfordalumni.org
Wed, 21 Aug 2002 14:52:44 -0700


After looking around in the code, I think I've figured out how to get
this to work.  Here it is, for the benefit of those who follow, and
for the benefit of myself if anyone has any corrections or insights:

The key is that a lot of the machinery is in PageTemplates/TALES.py,
which sort of explains things.  In particular it defines Engine and
Context.

ross@wheat:/usr/lib/zope/lib/python$ python
Python 2.1.3 (#1, Jul 29 2002, 22:34:51)
[GCC 2.95.4 20011002 (Debian prerelease)] on linux2
Type "copyright", "credits" or "license" for more information.
>>> from Products.PageTemplates import Expressions
>>> myvars = {'q1':0, 'q2':1}
>>> e = Expressions.getEngine()
>>> c = e.getContext(myvars)
>>> from Products.PageTemplates.ZRPythonExpr import PythonExpr
# the last argument in the next line should be an engine
# but it's ignored anyway, as far as I can tell.
>>> pe = PythonExpr('python', 'q1 or q2', c)
>>> pe(c)
1
>>> pe = PythonExpr('python', 'q1 and q2', e)
>>> pe(c)
0


An alternate interface appears to be
pe = e.compile('python: q1 or q2')
but this may pull in the ZRPythonExpr version of PythonExpr or the
ZPythonExpr version depending on some other settings whose values I'm
not sure of (search for those strings in Expressions.py).  The direct
route shown above still has a potential glitch, because the version of
PythonExpr that is directly instantiated may not match the one defined
in the context's engine.  I don't know if that can cause trouble.