Help please, with this code fragment

Joseph A Knapka jknapka at earthlink.net
Tue Jan 15 23:39:15 EST 2002


MikeK wrote:
> 
> The following code fragment, from Eckel's upcoming "Thinking in
> Python",
> does not work under Python 2.1, and the problem appears to be
related
> to
> namespaces.  I've worked with this for a couple of hours now,
trying
> to
> come up with a workable alternative/understanding using my limited
> knowledge of Python.  Could someone give me a hand?
> 
> The code is supposed to take a class method and wrap it in code
that
> uses
> a class object-level mutex to synchronize the getting/setting of
some
> data that might be get/set by multiple callers of its methods.
Python
> 2.1 has trouble with the 'method' argument to synchronized(),
telling
> me that when used in function 'f()', it is not found.  I have a
> general understanding that this is due to the changes to
namespaces in
> 2.1, but don't know how to change the code to get the equivalent
> functionality.
> 
> ===Begin code===

Here, add

from __future__ import nested_scopes

> import threading
> 
> def synchronized(method):
>     def f(*args):
>         self = args[0]
>         self.mutex.acquire()
>         try:
>             return apply(method, args)
>         finally:
>             self.mutex.release()
>     return f
> ===End code===

The warning (at compile time)/error (at run time) occurs
because without the nested_scopes import, names from
enclosing scopes are not visible; instead, the old
"local,global,builtins" rule is used.

HTH,

Cheers,

-- Joe
"I should like to close this book by sticking out any part of my neck
 which is not yet exposed, and making a few predictions about how the
 problem of quantum gravity will in the end be solved."
 --- Physicist Lee Smolin, "Three Roads to Quantum Gravity"



More information about the Python-list mailing list