Metaclass to make all methods of a class thread-safe
Michele Simionato
michele.simionato at gmail.com
Mon Sep 27 05:41:46 EDT 2004
Irmen de Jong <irmen at -nospam-remove-this-xs4all.nl> wrote in message news:<415728eb$0$78753$e4fe514c at news.xs4all.nl>...
> Hi,
> I've developed the Metaclass below, because I needed a way
> to make a bunch of classes thread-safe.
> I didn't want to change every method of the class by adding
> lock.aqcuire()..lock.release() around the existing code.
> So I made a metaclass that essentially replaces every method
> of a class with a 'wrapper' method, that does the locking,
> invocation, unlocking.
>
> Is this the right approach? It seems to work fine. But I have
> very little experience with metaclass programming, so I'd like
> to hear some feedback.
>
> Thanks !!
>
> --Irmen de Jong.
Well, it looks okay, but consider the following:
1. you have a (metaclass) static method and a (metaclass) classmethod
which could be replaced by simple functions external to the metaclass;
this would make the code much easier to read and to understand; I don't
buy the argument that they should logically stay in the metaclass, it
is enough if they stay in the same module of the metaclass, not inside it;
2. the metaclass will automagically wrap even methods of subclasses, without
you knowing it; consider using a naming convention (es. only methods
starting with "t_" are magically wrapped); if still
you want the magic, consider defining a name convention such as methods
starting with a given prefix are NOT magically wrapped;
4. built-in methods and all the objects which are non instances of FunctionType
will be not wrapped; you may want this or not;
5. consider using decorators to wrap the methods you want to be
thread safe: they a more esplicit and easier to understand solution;
also in this way you will avoid the (possible) issue of metaclass
conflicts.
6. However, if you want to enhance a code which is already written
with a minimal change of the source code, the metaclass is the
simplest solution indeed.
Just my 0.02c,
Michele Simionato
More information about the Python-list
mailing list