[Python-Dev] Odd new-style class new behavior (original) (raw)

Guido van Rossum guido@python.org
Sat, 30 Mar 2002 13:27:20 -0500


On 30 Mar 2002, Michael Hudson wrote: > Kevin Jacobs <jacobs@penguin.theopalgroup.com> writes: > > Suppose I define: > > > > class Foo(object): > > def new(cls): > > return 1 > > > > class Bar(object): > > def new(cls): > > return [1,2,3] > > > > Python 2.2 returns: > > print Foo() > > > 1 > > print Bar() > > > [] > > > > I would expect that Bar() should return [1,2,3]. Am I running into some > > clever undocumented feature or a bug? > > Is tpinit being called on the returned list?

Correct.

I suspect that the object construction code would check the result of tpnew to see if the expected type. If not, tpinit should not be called on the instance. I suspect that this check must already be there, or else none of these cases would work at all.

It calls the tp_init of the returned type.

Anyhow, I won't know what is really happening for sure until Monday, when I can run this through gdb. However, some more data points: returning dictionaries, tuples, strings, classic object instances, and user-defined new-style classes all seem to work. Only lists seem to behave this way.

Because only lists have a tp_init that resets the object.

Guido, can you clarify what the "correct behavior" should be for the above cases? Once I know that, I will happily supply a corrective patch if one is necessary.

Correct behavior is not to return a different type unless you know what its init does.

We're going to document each type's new and init, and you're welcome to help.

--Guido van Rossum (home page: http://www.python.org/~guido/)