deleting, then re-importing a class method

Peter Otten __peter__ at
Thu Jan 21 11:51:01 CET 2010

Robert P. J. Day wrote:

>   (once again, never ashamed to ask the dumb questions.)
>   still playing with python3, and testing whether i can
> delete/unimport a specific method, then re-import it:
>>>> import sys
>>>> print(sys.__doc__)
> ... blah blah blah ...
>>>> del(sys.__doc__)
>>>> print(sys.__doc__)
> module(name[, doc])
> Create a module object.
> The name must be a string; the optional doc argument can have any
> type.
>   ok, now that i've deleted just that member of "sys", can i re-import
> it?  i know this doesn't seem to work:

Actually you haven't:

>>> import sys
>>> del sys.__doc__
>>> hasattr(sys, "__doc__")

>>>> import sys
>   or is there an operator other than "import" that more represents a
> full refresh of a class?


> rday
> p.s.  no, i don't have a valid application of the above, i'm just
> trying to break things.

That is indeed likely to happen:

Python 3.1.1+ (r311:74480, Nov  2 2009, 15:45:00)
[GCC 4.4.1] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import os
>>> walk = os.walk
>>> del os.walk
>>> hasattr(os, "walk")
>>> import imp
>>> imp.reload(os)
<module 'os' from '/usr/lib/python3.1/'>
>>> os.walk
<function walk at 0x18c86b0>
>>> os.walk is walk

So you have to two distinct walk() functions now. This becomes especially 
nasty when

isinstance(obj, module.Class)

tests begin to fail because the module and the class was reloaded, but obj 
is an instance of module.Class before the reload.


More information about the Python-list mailing list