print and Python-2.* and Python-3.* consistency

When Python is the interpreter, what is a good
design for the interface to the basic NEURON

Moderator: hines

Post Reply
Site Admin
Posts: 1596
Joined: Wed May 18, 2005 3:32 pm

print and Python-2.* and Python-3.* consistency

Post by hines » Sat Aug 29, 2009 4:21 pm

I'm extending the NEURON+Python interface so it works with Python-3.1 and
need to make a decision about what to do about the behavior of __str__(), __repr__(),
The fragment

Code: Select all

from neuron import h, hclass
v = h.Vector()
print v, str(v), type(v)
class MyVector(hclass(h.Vector)):
m = MyVector()
print m, str(m), type(m)
in Python 2.5 prints

Vector[0] <hoc.HocObject object at 0x1561bcd8> <type 'hoc.HocObject'>
<__main__.MyVector object at 0x2b21e819d668> <__main__.MyVector object at 0x2b21e819d668> <class '__main__.MyVector'>

and in Python 3.1 (after converting print ... to print ( ... )) prints

<hoc.HocObject object at 0x2b60921cf810> <hoc.HocObject object at 0x2b60921cf810> <class 'hoc.HocObject'>
<__main__.MyVector object at 0x2b60921a0050> <__main__.MyVector object at 0x2b60921a0050> <class '__main__.MyVector'>

That is, Python 3.x no longer cares about the tp_print field which I have been using to print information about the HocObject.
If I instead move the tp_print functionality to the tp_repr field, then
Python 2.5 prints

Vector[0] Vector[0] <type 'hoc.HocObject'>
Vector[1] Vector[1] <class '__main__.MyVector'>

and Python 3.1 prints

Vector[0] Vector[0] <class 'hoc.HocObject'>
Vector[1] Vector[1] <class '__main__.MyVector'>

Notice they are the same but the HocObject baseclass __repr__ is called so that the subclass name is not printed for the MyVector case.
So for reasons of consistency and subclass determination, I'm considering NOT defining my own __repr__ for HocObject and instead moving the tp_print functionality to an
hname() method. i.e the underlying type within HocObject would be found through v.hname() and m.hname().
This means that if you want the old behavior of
print v
you have to write
print v.hname()

If anyone can think of a better policy, let me know.

Post Reply