Metaclass to make all methods of a class thread-safe
Irmen de Jong
irmen at -nospam-remove-this-xs4all.nl
Mon Sep 27 21:22:48 CEST 2004
Michele Simionato wrote:
> Irmen de Jong <irmen at -nospam-remove-this-xs4all.nl> wrote in message news:<415728eb$0$78753$e4fe514c at news.xs4all.nl>...
>>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.
>>--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;
Agreed, I was just modeling it after some example metaclass code that I found
on ASPN cookbook. The metaclass itself will only be a few lines then :-)
> 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;
This is good advice. I started by not wrapping methods with '__' prefix...
> 4. built-in methods and all the objects which are non instances of FunctionType
> will be not wrapped; you may want this or not;
Built-in methods such as?
About the other objects: I only cared about wrapping class methods.
Shouldn't I have / should I use something else than FunctionType?
There is one thing though; methods that you're accessing trough the
class's __dict__ (which is what the meta class is doing, right?)
are of type <function>, rathar than <instancemethod> which I expected:
>>> class A:
... def meth(self): pass
Why is this?
> 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
No decorators, nooo sir, it must work on Python 2.3 too :)
> 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.
Thanks for your comments, Michele.
More information about the Python-list