Testing changes to Python code on the fly: reload() + alternatives?

Keith keith.hughitt at gmail.com
Tue Apr 12 15:26:48 EDT 2011


Hi all,

I have a couple of questions that I was hoping people might be able to provide suggestions on.

1) Is it possible to reload a class using the reload() method? For instance, suppose you have the following files:

my_module/
  __init__.py
  MyClass.py

#init.py
from MyClass import MyClass

#MyClass.py
class MyClass:
    def __init__(self):
        print("Before...")

Is it possible to load the class, change the print statement (e.g. print("after...")), and have the changes take effect right away?

The above method does not work:

 In [1]: import my_module

 In [2]: my_module.MyClass()
 Before...
 Out[2]: <my_module.MyClass.MyClass instance at 0x8f5d16c>

 In [3]: reload(my_module)
 Out[3]: <module 'my_module' from 'my_module/__init__.pyc'>

 In [4]: my_module.MyClass()
 Before...
 Out[4]: <my_module.MyClass.MyClass instance at 0x8fca1ec>

Is there anyway to make this work while keeping MyClass in the main "my_module" namespace?

2) More generally though, what is the best way to go about testing changes to code as you are writing it?

It would be very convenient to be able to use reload() along the lines of the above so that I could test changes to a small part of some class/function/etc without having to reload the entire state from scratch.

Another option of course would be to just run everything as a standalone script, but then you lose the ability to be able to easily inspect the objects you are working and change them on the fly, except perhaps by using PDB.

Any suggestions would be greatly appreciated.

Thanks!
Keith



More information about the Python-list mailing list