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

K

Keith

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
 
T

Terry Reedy

1) Is it possible to reload a class using the reload() method?

Yes, but instances of the old version will remain instances of the old
version, which will not go away until all its instances and other
references go away. So reload is deceptive, which is why it was
semi-hidden away in 3.x in the inspect module.
16039320

2) More generally though, what is the best way to go about testing changes to code

Restart from the beginning.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,744
Messages
2,569,482
Members
44,900
Latest member
Nell636132

Latest Threads

Top