[Python-Dev] function attributes as "true" class attributes & reclamation error

Skip Montanaro skip@mojam.com (Skip Montanaro)
Sat, 6 Jan 2001 09:35:20 -0600 (CST)


You know, I thought of something (which was probably already obvious to the
rest of you) while perusing Barry's patch.  Attaching function attributes to
unbound methods could really function like C++ static data members.  You'd
have to write accessor functions to make setting the attributes look clean,
but that wouldn't be all bad.  Precisely because you couldn't modify them
through the bound method, there's be no chance you could make the mistake of
modifying them that way and having them transmogrify into instance
attributes.

Here's a quick example:

    class C:
      def __init__(self):
	self.just_resting()
      __init__.howmany = 0

      def __del__(self):
	self.hes_dead()

      def hes_dead(self):
	C.__init__.howmany -= 1

      def just_resting(self):
	C.__init__.howmany += 1

      def howmany(self):
	return C.__init__.howmany

    def howmany():
	return C.__init__.howmany

    c = C()
    print c.howmany()
    d = C()
    print d.howmany()
    del c
    print d.howmany()

After applying Barry's patch, if I execute this script from the command line
it displays

    1
    2
    1

as one would expect, but then catches an attribute error during cleanup:

    Exception exceptions.AttributeError: "'None' object has no attribute
    '__init__'" in <method C.__del__ of C instance at 0x80ffc14> ignored

If I add "del d" to the end of the script the exception disappears.  I
suspect there is a cleanup order problem of some sort.  It seems like C is
getting reclaimed before d (not possible), or that d's __class__ attribute
is set to None before its __del__ method is called.  Is this a known problem
or something introduced by Barry's patch?

Skip