Skip to content
Advertisement

Possible to create a @synchronized decorator that’s aware of a method’s object?

I’m trying to create a @synchronized wrapper that creates one Lock per object and makes method calls thread safe. I can only do this if I can access method.im_self of the method in the wrapped method.

JavaScript

(1) What’s confusing is that the func parameter passed to my decorator changes type before it gets passed into the wrapper-generator. This seem is rude and unnecessary. Why does this happen?

(2) Is there some decorator magic by which I can make method calls to an object mutex-ed (i.e. one lock per object, not per class).

UPDATE: There are many examples of @synchronized(lock) wrappers. However, really what I want is @synchronized(self). I can solve it like this:

JavaScript

However, because its much more efficient, I’d prefer:

JavaScript

Is this possible?

Advertisement

Answer

Go read:

and in particular:

The wrapt module then contains the @synchronized decorator described there.

The full implementation is flexible enough to do:

JavaScript

Along with context manager like usage as well:

JavaScript

Further information and examples can also be found in:

There is also a conference talk you can watch on how this is implemented at:

Advertisement