MetaPython

Ouroboros

...another project with a dire need for a better logo

Author:Rick Copeland
Date:April 9, 2009

MetaPython: What is It?

Why Macros?

Inadequate Syntax in Your Language

Common example for Lisp/Scheme: while:

(defmacro while (expression &body body)
  ...)
Already got one

I told him we already got one!

Why Macros?

Class Factories

  • Example: collections.namedtuple in Python 2.6
    • Giant string template that is then exec ed
    • Already ugly and could use a better syntax
  • unittest.TestCase factories
    • One TestCase per browser
      • Avoid using type(...) constructor
      • Use something more obscure instead!

Why Macros?

Avoid Expensive Evaluations

  • Example:

    log.debug('Some value: %s',
              expensive_computation(...))
    
    • No matter what the log_level is, expensive_computation() will still be called
  • Possible (ugly) fix:

    if loglevel >= logging.DEBUG:
        log.debug(...)
    

Why Macros?

Performance

  • Possible to inline function calls
  • Probably least compelling
  • Used to do this in Lisp, but Lisp grew inline functions

MetaPython Mechanics

How do you actually use this stuff?

Import-Time Code

Code Quoting

Actual Usage

Example: Named Tuples

Original Code

def namedtuple(typename, field_names):
    # ... lots of setup
    template = '''class %(typename)s(tuple):
        ... lots of text ...''' % locals()
    for i, name in enumerate(field_names):
        template += '...'
    # ... snip ...
    try:
        exec template in namespace
    except SyntaxError, e:
        raise SyntaxError(e.message...)
    return result = namespace[typename]

Example: Named Tuples

Original Usage:

Point = namedtuple('Point', 'x y')

Easy to get wrong:

MyPoint = namedtuple('Point', 'x y')

Example: Named Tuples

New Code

def namedtuple(typename, *field _names):
    ...
    defcode result:
        class $<typename>(tuple):
            ...
    return result

New Usage

$namedtuple(?Point, ?x, ?y)

Status, Docs, Development

Questions?

Your writing is a shot in the dark? Use your time and efforts wisely - buy essays online! | wifi planner mac | Description of Plague