Tuesday 19 October 2004 — This is more than 20 years old. Be careful.
I was working on a Python project, and reached a conundrum about interfaces. I know they are worthwhile in general, but in a dynamic language like Python their position is a bit fidgety. Read more about my Quest for Pythonic Interfaces.
Comments
An application or so a go I tried to use an internal dictionary to store objects for "implemented" interfaces. I overrode the getattr method in the base class to check this dictionary for objects of a certain type and run the correct method, if the dictionary had an object with a method. It was heavy, bloated, and problematic, but I think the idea was a sound one that's worthy of further exploration.
My 2% of a dollar.
Keith
That said, using them will be as easy as simply creating a base class that raises NotImplementedError for all its methods. There's a significant overhead to being explicit in your interfaces; but if you're already convinced of the benefit, then maybe you're ready to make those changes.
I realize you say that's the path to "one interface per method", but don't all interfaces walk that path eventually? I mean, how else would you expect to do it in Java or C++? Really, in my experience, it's uncommon to have really wide interfaces. Most are in the 1-5 method range, I think, and that's a *good* thing, because it means you're keeping concerns separate.
Now, if you want to use PyProtocols, you can usually separate these concerns on either a class-by-class or even instance-by-instance basis using adapters, but of course your code may become somewhat more verbose due to the addition of adapter classes. But your code will also be more modular, because the details specific to an entire area of concern can then be factored out from the pure "domain model" code.
My gut feeling is you are trying to make Python be something it doesn't want to be. That's probably not a good thing.
Add a comment: