A Python pattern: Mutating Proxies
Over the course of the Python code that I've written, I've noticed certain patterns that seem to reoccur relatively frequently. One of my common ones is a pattern that I'll call the Mutating Proxy.
Python doesn't have much use for plain proxy objects, objects that just relay things to another one, since duck typing means that you can usually just use the original object instead. A mutating proxy is a proxy that's used in order to change the behavior of the underlying object, adding things or changing the behavior of existing things.
(For example, I have used a mutating proxy to give sockets a total
close() timeout, instead of just their timeout on
Mutating proxies are sometimes but not always implemented as subclasses of the original object class. The classical reason not to subclass is if you don't generate the objects you want to proxy, so you have no good way to get them created as instances of your subclass. If you want to mutate the behavior of SSL sockets, for example, you will be wrapping them since they get handed to you by the underlying C code in the socket module.
(Another reason not to subclass is if you're only doing a partial implementation of your mutation. Since a real proxy passes only the bits you've implemented, attempts to use unsupported stuff will fail right away instead of sort of working.)
Comments on this page:Written on 14 January 2008.