Page 1 of 1

multiple interpreters/multiple levels of py/N nesting

Posted: Fri Dec 24, 2010 9:57 am
by wwlytton
A question and a problem.

Q: What are the various advantages/disadvantages of choosing one of these many available routes to running NEURON with python?:
1. nrniv using nrnpython(); 2. nrniv -python; 3. python with import; 4. ipython with import (to get pylab); 5. sage with import
Obviously a major disadvantage of solution 1 is the need to type nrnpython("command") a lot so can leave that out.

Here's the Problem:
I stumbled on a problem yesterday for code entered at the command line that didn't occur when importing a file: Python builtins are not directly available from the doubly nested python interpreter. This may seem idiotic, but it came up in practice because we were starting in nrnpy and loading hoc files that then tried to load py files using the py builtin execfile()
(this failed interactively but worked in batch mode)

eg -- this works
$ nrniv -python
...
>>> abs(-5) # built-in absolute value function
5

this doesn't (I'm illustrating here as a triple nesting from hoc to show 1st level p.command() functionality; this would be double nesting starting from nrniv -python)

nrniv ...
oc>objref p,q
oc>p=new PythonObject() // nested py interpreter
oc>p.abs(-5) // 1st nesting ok
5
oc>nrnpython("from neuron import h") // second nesting
oc>p.h.p.abs(-5) // 3rd implicit nesting fails
AttributeError: 'module' object has no attribute 'abs' ...
oc>p.h.p.__builtins__.abs(-5) // but can pick it up with this trick
5
p.h("q = new PythonObject()") // 3rd explicit nesting doesn't help; still in same hoc interpreter anyway

a workaround is eg
p.h.p.abs=p.h.p.__builtins__.abs
then
p.h.p.abs(-5) // works

Mike took a look at this and noted that problem is somewhere in

relevant code it is nrn/src/nrnpython/nrnpy_p2h.cpp
PyObject* nrnpy_hoc2pyobject(Object* ho) {...

The other obvious answer (lest anyone is tempted to tell me) is not to use double, triple or quadruple interpreter nesting.