[Petal] [IDEA] Hash with params

Evan Simpson evan at 4-am.com
Mon Sep 8 15:35:55 BST 2003


Steve Purkis wrote:
> And I assume it would be possible to define prefixes that variables as 
> arguments so that it would be possible to say "some/hash/key:somevar" 
> and "some/list/item:someindex"?

Sure!  The prefix implementation can do whatever it likes with the 
argument, including treat it as a variable name, convert it to a number, 
or ignore it entirely.

In ZPTs, prefixes are implemented by a pair of functions dubbed the 
compiler and the handler.  At least one of the two must be provided.

If a compiler is provided, the prefix and argument strings are passed to 
it (a single compiler could be used for multiple prefixes) and its 
return value replaces the argument string in further processing.  This 
allows for argument parsing, error checking, and other preprocessing 
that doesn't depend on context.

If a handler is provided, then it is called during path traversal.  The 
prefix string, argument value, current traversal object, remaining 
traversal path segments, and the execution context (variable namespaces) 
are passed to it.  The returned object is used for the next traversal step.

As an optimization the compiler is called lazily, the first time the 
path is traversed, and the argument value is cached.

Here's the Python code that defines the builtin 'var' prefix:

# 'var:x' is replaced with the value of variable 'x'
def var_compiler(prefix, arg):
     arg = arg.strip()
     if not _valid_name(arg):
         raise CompilerError, ('"%s" is not a valid variable name'
                               % arg)
     return arg
def var_handler(prefix, arg, object, path, econtext):
     path.append(econtext.vars[arg])
     return object
builtins['var'] = PathPrefix(var_compiler, var_handler)


Cheers,

Evan @ 4-am



More information about the Petal mailing list