A Python pattern: Mutating Proxies

January 14, 2008

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 connect() to close() timeout, instead of just their timeout on individual operations.)

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:

From 194.8.197.205 at 2008-01-15 05:21:25:

I thought “mutating proxies” would be ones that shift shape in response to whatever (eg. something like the Object::Lazy Perl module). A better term for what you’re talking about might be “decorating proxies.”

Aristotle Pagaltzis

By cks at 2008-01-15 11:50:12:

I think of these as 'mutating' because they change the behavior of the underlying object that they are pretending to be; to the outside world, they are a mutated version of the original. By contrast, the Perl example may change itself internally but it tries to look like the original to the outside world.

Written on 14 January 2008.
« The robot logic of ZFS snapshots and quotas
What applications are actually crucial at a university »

Page tools: View Source, View Normal.
Search:
Login: Password:

Last modified: Mon Jan 14 23:25:24 2008
This dinky wiki is brought to you by the Insane Hackers Guild, Python sub-branch.