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.)

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, Add Comment.
Login: Password:
Atom Syndication: Recent Comments.

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