Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to develop a Python module/package without having to restart the interpreter after every change?

I am developing a Python package using a text editor and IPython. Each time I change any of the module code I have to restart the interpreter to test this. This is a pain since the classes I am developing rely on a context that needs to be re-established on each reload.

I am aware of the reload() function, but this appears to be frowned upon (also since it has been relegated from a built-in in Python 3.0) and moreover it rarely works since the modules almost always have multiple references.

My question is - what is the best/accepted way to develop a Python module/package so that I don't have to go through the pain of constantly re-establishing my interpreter context?

One idea I did think of was using the if __name__ == '__main__': trick to run a module directly so the code is not imported. However this leaves a bunch of contextual cruft (specific to my setup) at the bottom of my module files.

Ideas?

like image 951
Brendan Avatar asked Jan 01 '10 21:01

Brendan


2 Answers

A different approach may be to formalise your test driven development, and instead of using the interpreter to test your module, save your tests and run them directly.

You probably know of the various ways to do this with python, I imagine the simplest way to start in this direction is to copy and paste what you do in the interpreter into the docstring as a doctest and add the following to the bottom of your module:

if __name__ == "__main__":
    import doctest
    doctest.testmod()

Your informal test will then be repeated every time the module is called directly. This has a number of other benefits. See the doctest docs for more info on writing doctests.

like image 179
Will Hardy Avatar answered Oct 02 '22 08:10

Will Hardy


Ipython does allow reloads see the magic function %run iPython doc

or if modules under the one have changed the recursive dreloadd() function

If you have a complex context is it possible to create it in another module? or assign it to a global variable which will stay around as the interpreter is not restarted

like image 37
mmmmmm Avatar answered Oct 02 '22 08:10

mmmmmm