Archive for March, 2010

Python: Reloading a class definition at runtime

March 14th, 2010

Python comes with a very useful function called “reload”, which allows to dynamically reload the code of a given module at runtime. This technique is quite useful if one wants for example to reload some part of a larger application without having to close and restart the whole system.

Personally, I often use “reload” to dynamically update classes when doing rapid prototyping. By this technique I can for example reload a single widget of a GUI without having to restart the whole program, saving me tons of precious development time.

To provide the “reload” functionality in an object-oriented fashion, I just wrote a small class called “Reloadable”. This class provides a function “reloadClass” that takes care of the whole reload process: First, it calls “reload” for the module that defined the original class (the name of which is stored in the variable “self.__module__”), fetches a reference to the reloaded class type (by using the class name given in “self.__class__.__name__”) and replaces the “self.__class__” variable by this new type. After this, the class instance will have all its functions and variables replaced by their reloaded version but will nevertheless keep all instance variables that were already defined. Finally, “reloadClass” calls the function “onReload”, which can be redefined in a subclass to implement some specific reloading tasks. Easy, isn’t it? Please also note that all other instances belonging to the reloaded class will stay unaffected by this operations.

Here is the code snippet that defines “Reloadable”:

import sys
class Reloadable():
 
  #Reload the module that defines the class and replace the "__class__" variable with a new instance of the class.
  def reloadClass(self):
    newModule = reload(sys.modules[self.__module__])
    self.__class__ = eval("newModule.%s" % self.__class__.__name__)
    self.onReload()
 
  #Re-implement this function in the derived class to perform specific tasks after the reload (e.g. call "__init__")
  def onReload(self):
    pass

There is also a nice code snippet on code.activestate.com that will automatically reload all instances of a class when the corresponding module is reloaded.

Presentation: Python for Scientists

March 9th, 2010

This is a presentation I gave at our weekly group seminar. It discusses the use of the programming language Python in a scientific environment, putting emphasis on data acquisition, processing and presentation. Enjoy!