RFC -- Hygienic Macros in Python
Jason Orendorff
jason at jorendorff.com
Tue Feb 12 02:03:12 EST 2002
phil hunt wrote:
> The way i would do it, if I was implementing it, would be something
> like:
>
> defmacro synchronized(lock_expr, code_block):
> local lock
> lock = ^lock_expr
> lock.acquire()
> try:
> ^code_block
> finally:
> lock.release()
>
> Where the "local lock" declaration means something like: in the
> current namespace create a local variable name that doesn't clash with
> anything else.
So "local" is stripped out of the list of tokens that constitutes
the "synchronized" macro?
This seems to move away, a bit, from your previous notion that
macros should be expanded without any extra processing. If so,
then the question becomes: why shouldn't "local" be the default?
My experience is that anything other than lexical scoping always
ends up being a real pain. Names in classes, functions, and
top-level module code is all lexically scoped. They should be
within defmacro too, by default.
> In something like C++ you could just put {...} round it can define
> variables within that and they'd be local to it, but you can't do
> that in Python.
As a digression, here's the best I can do in C++.
// synchronized() in C++
// totally untested, might not compile
// Locking interface, which lockable objects must implement
class ILock {
public:
virtual void acquire() = 0;
virtual void release() = 0;
};
class Locker {
public:
Locker(ILock &lock) : _lock(lock) { _lock.acquire(); }
~Locker() { _lock.release(); }
operator bool() { return true; }
private:
ILock & _lock;
};
// Uses the unfamiliar standard C++ "if (decl)" syntax
#define synchronized(lock_expr) \
if (Locker _synchronized_magic_object(lock_expr))
## Jason Orendorff http://www.jorendorff.com/
More information about the Python-list
mailing list