RFC - Hygienic macros in Python

Jason Orendorff jason at jorendorff.com
Wed Feb 6 12:59:22 EST 2002


For the benefit of the discussion, here is another
example of what a macro could do:

  # I hope this syntax is readable; it's just an
  # example of how Courageous might choose to
  # have things look.
  defmacro synchronized(lock_expr, code_block):
      lock = ^lock_expr
      lock.acquire()
      try:
          ^code_block
      finally:
          lock.release()

This defines a new "synchronized" statement,
such as thread-happy people are always looking for
in Python:

  synchronized fnord.lock:
      fnord.foo()
      fnord.baz(bar)

Another possible example.  Suppose you have written
a library that provides expect-like functionality
and you wish to add that functionality to Python's
syntax (because it's very awkward to call it as a
library; you have to wrap all the code in
functions - very inconvenient).

The syntax you want is like this:

  scan myfile:
      case r'[Ll]ogin':
          send(username + '\n')
      case r'[Pp]assw(or)?d':
          send(password + '\n')
      case r'[%$>]':
          foo()
          bar()
          send(command + '\n')

Using a macro, you could add this syntax to the language.
(I don't know what the code for the macro itself would look
like.)

Ruby allows a small-but-useful subset of this functionality,
but the idea really comes from Lisp.  The "hygienic" part comes,
I think, from Scheme.

## Jason Orendorff    http://www.jorendorff.com/




More information about the Python-list mailing list