[Python-Dev] assigning to new-style-class.__name__

Michael Hudson mwh@python.net
26 Nov 2002 15:06:38 +0000


My (very) recent patch #635933 allows assignment to both __name__ and
__bases__ of new-style classes.  Given that the code for __bases__ is
much more complicated, it's a little odd that __name__ is the one
still giving me headaches.

It's all to do with dots.

An extension type like (e.g.) time.struct_time is created with a
tp_name of 'time.struct_time' which the accessors for __module__ and
__name__ translate thusly:

>>> time.struct_time.__name__
'struct_time'
>>> time.struct_time.__module__
'time'

User defined new-style classes _seem_ to behave similary:

>>> class C(object):
...  pass
... 
>>> C.__name__
'C'
>>> C.__module__
'__main__'

but under the hood it's quite different: tp_name is just "C" and
'__module__' is a key in C.__dict__.  This shows up when in:

>>> C.__name__ = 'C.D'
>>> C.__name__
'D'
>>> C.__module__
'C'

which isn't really what I would have expected.

What I'd like to do is treat heap types and not-heap types distinctly:

For non-heap types, do as we do today: everything in tp_name up to the
first dot is __module__, the rest is __name__.  You can't change
anything here, no worries about that.

For heap types, __module__ is always __dict__['__module__'], __name__
is always tp_name (or rather ((etype*)type)->name).

Comments?  I think this is fine, so long as there aren't heap types
that are created by some wierd means that leaves them without
"'__modules__' in t.__dict__".

(If someone does

del t.__dict__['__modules__']

they deserve to lose, but we shouldn't crash.  I don't expect this to
be a problem).

Cheers,
M.

-- 
  First time I've gotten a programming job that required a drug
  test.  I was worried they were going to say "you don't have
  enough LSD in your system to do Unix programming".   -- Paul Tomblin
               -- http://home.xnet.com/~raven/Sysadmin/ASR.Quotes.html