16 Oct 2005

Modules and Singletons

I was in a design patterns class the other day, and singletons were being discussed. The instructor said that the classic example of a singleton is a window manager. That set me thinking - if you aren't going to have multiple instances of it, why should it be a class? Couldn't it be a module? Probably the answer is that you do want multiple implementations of a window manager; you just don't want them instantiated at once. I can imagine a system where you instantiate one implementation (subclass) of WindowManager at startup and use that till shutdown without being able to instantiate another. If you're using a crippled language like Java, you can't think beyond this.

But if you're using Python, new avenues open up. You can represent each window manager by a module and dynamically decide which one to import. As long as the modules are interface-compatible (in the sense of the contract, not the narrow syntactic sense of the same list of methods [perhaps this is part of the reason why python does not have an explicit notion of interfaces, because what can be checked is a small part of what must hold]), everything works. You could get a module object and access members of the module using the usual dot operator. Interestingly, what makes this work is that modules are objects (in the sense of having attributes that can be callable); they just happen to be managed automatically by the language rather than needing to be taken care of by the programmer. So the question is not exactly do we use objects, but: do we want to take care of these objects explicitly or leave it to the language? Obviously, leave it to the language when possible. One more case of an abstraction allowing us to forget some details and so save work.

You could also do this using import as. (Till now I didn't understand why anybody would want to import a module using a different name.)

Python seems to have very powerful abstractions and a lot of hooks where you can change things.

No comments:

Post a Comment