My favorite design pattern in Python

I’ve noticed some days ago that I mainly used one design pattern in my scientific (but not only) code, the registry. How does it work? A registry is a list/dictionary/… of objects, applications add a new entry if it is needed, and then a user can tap into the registry to find the most adequate object for one’s purpose.

In fact, the registry is one of the best replacement for the switch statement. Indeed, it is far more modular as new cases can be introduced and deleted, and it is more readable as well.

I used a registry in several pieces of code:

  • when I’m playing with manifold learning, I have a registry of the dimensionality reduction tools and I can choose the one that fits my needs (given as a commandline argument);
  • I refactored scikits.openopt so that a registry contains the different solver wrappers, and now people can add their own wrapper in the dictionary, the key being the name of the solver and the value is a string with the package hierarchy to use;
  • I’m trying to develop a JXTA implementation in Python, and the registry shows up everywhere, or almost. For instance, as in the original, Java, implementation, the advertisements are stored in a dictionary, and new kind of advertisements can be registered efficiently. The parsing of each advertisement is also done with a class registry.

Python, with is dynamic and duck typing, is naturally inclined to use registers, IMHO. This is more scientific-oriented coding, but the ease of use of a registry is very helpful in my everyday work.

Here is a sample of the automatic use in pyP2P:

from advertisement_core import *
from peer_advertisement import *
class Advertisement(object):
  pass

registry = {}
import advertisement_core

class PeerAdvertisement(advertisement_core.Advertisement):
  pass

advertisement_core.registry["PA"] = PeerAdvertisement

This way, when the module is imported, the registry is also automatically populated.

1 thought on “My favorite design pattern in Python

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.