Class destructor -- strange behaviour

Jason tenax.raccoon at gmail.com
Fri Dec 7 12:00:11 EST 2007


On Dec 6, 2:51 pm, Spes <Vlastimil.Ho... at gmail.com> wrote:
> Hi,
>
> I have this simple code:
> | #!/usr/bin/python
> | import codecs
> | import re
> | from copy import deepcopy
> |
> | class MyClass(object):
> |   def __del__(self):
> |     deepcopy(1)
> |
> | x=MyClass()
>
> but I get an error:
> | Exception exceptions.TypeError: "'NoneType' object is not callable"
> in <bound method MyClass.__del__ of <__main__.MyClass object at
> 0x6fcf0>> ignored
>
> The problem disappears if I do anything of this:
> 1. change
>      - from copy import deepcopy
>      + import copy
>     and call directly copy.deepcopy(1)
>
> or
> 2. don't store object to variable `x'
>
> or
> 3. don't import module `re'
>
> The first solution is OK, but I would like to know why it behaves so
> strange. We have tested on:
>
> - Mac OS X Tiger for PPC
> Python 2.3.5 (#1, Mar 20 2005, 20:38:20)
> [GCC 3.3 20030304 (Apple Computer, Inc. build 1809)] on darwin
>
> - Linux 64bit and 32bit
> Python 2.4.4 (#1, Oct 30 2007, 14:31:50)
> [GCC 4.1.2 (Gentoo 4.1.2 p1.0.2)] on linux2
> Python 2.5 (r25:51908, Jan 12 2007, 13:57:15)
> [GCC 4.0.2 20051125 (Red Hat 4.0.2-8)] on linux2
>
> Thanks for the explanation,
> Vlasta

Gabriel nailed the problem down.  Another solution is to explicitly
import module names in your destructor, ie:

def __del__(self):
  from copy import deepcopy
  deepcopy(1)

This guarantees that your destructor has "deepcopy" binding that you
want, even if the name has already been reassigned to None in your
current module by the interpreter as it is shutting down.

  --Jason



More information about the Python-list mailing list