The PEAK Developers' Center   Diff for "PEAK-Rules/Predicates" UserPreferences
 
HelpContents Search Diffs Info Edit Subscribe XML Print View Up
Ignore changes in the amount of whitespace

Differences between version dated 2010-08-12 08:47:43 and 2011-08-31 21:12:05 (spanning 2 versions)

Deletions are marked like this.
Additions are marked like this.

calls where the second argument is a constant, and ``type(x) is y`` expressions
where `y` is a constant::
 
    >>> from peak.rules.criteria import Test, Signature, Classes
    >>> from peak.rules.criteria import Test, Signature, Conjunction
 
    >>> pe('isinstance(x,int)')
    Test(IsInstance(Local('x')), Class(<type 'int'>, True))

    Test(IsInstance(Local('x')), istype(<type 'str'>, False))
 
    >>> pe('not isinstance(x,(int,(str,unicode)))') == Test(
    ... IsInstance(Local('x')), Classes([
    ... IsInstance(Local('x')), Conjunction([
    ... Class(unicode, False), Class(int, False), Class(str, False)])
    ... )
    True

    True
 
    >>> pe('not issubclass(x,(int,(str,unicode)))') == Test(
    ... IsSubclass(Local('x')), Classes([
    ... IsSubclass(Local('x')), Conjunction([
    ... Class(unicode, False), Class(int, False), Class(str, False)])
    ... )
    True

    ... __builder__.bind(kw)
    ... return True
 
(Note: the above is not the actual implementation of the ``peak.rules.let()``
pseudo-function; the actual implementation uses a lower-level interface that
allows the keywords to be seen in definition order, so this is just a demo
to illustrate the operation of the ``meta_function`` decorator.)
 
To register your "meta function", you use ``@meta_function(stub_function)``::
 
    >>> from peak.rules.predicates import meta_function

    Test(Comparison(Local('x')), Range((Min, -1), (2, -1)))
 
 
Method Argument Binding
~~~~~~~~~~~~~~~~~~~~~~~
 
Any bindings defined in an expression can be converted into arguments for the
function associated with the rule that defined the bindings., by having its
first positional argument be a named argument tuple::
 
    >>> from peak.rules import abstract, when, around, let
    >>> def f(x): pass
    >>> f = abstract(f)
 
    >>> def dummy((q,z), x):
    ... print "Got q =", q, "and z =", z
    ... print "x was", x
 
    >>> when(f, "let(q=x*2, z='whatever') and True")(dummy)
    <function dummy ...>
 
    >>> f(42)
    Got q = 84 and z = whatever
    x was 42
 
This even works when you have a ``next_method`` argument after the tuple, and
even if your method is defined inside a closure::
 
    >>> def closure(y):
    ... def dummy2((a,b,c), next_method, x):
    ... print "a, b, c =", (a,b,c)
    ... print "y was", y
    ... return next_method(x)
    ... return dummy2
 
    >>> around(f, "let(a='a', b=x*3, c=b+23)")(closure(99))
    <function dummy2 ...>
 
    >>> f(42)
    a, b, c = ('a', 126, 149)
    y was 99
    Got q = 84 and z = whatever
    x was 42
 
At the moment, this actually works by recalculating the expressions in a
wrapper function that then invokes your original method, so it's more of a DRY
thing than an efficiency thing. That is, it keeps you from accidentally
getting your rule and your function out of sync, and saves on retyping or
copy-pasting.
 
(Future versions of PEAK-Rules, however, may improve this so that the bindings
aren't recalculated at every method level, or perhaps aren't recalculated at
all. It's tricky, though, because depending on the calculations involved, it
might be more efficient to redo them than to do the dynamic stack inspection
that would be needed to locate the active expression cache! So, in that event,
the main value would be supporting at-most-once execution of expressions with
side-effects.)
 
 
Custom Predicate Functions
==========================
 
The ``@expand_as`` decorator lets you specify a string that will be used in
place of a function, when the function is referenced in a condition.
 
Here's a trivial example::
 
    >>> from peak.rules import expand_as, value
 
    >>> def just(arg): pass
 
    >>> expand_as("arg")(just)
    <function just ...>
    
    >>> def f(x): pass
 
    >>> when(f, "x==just(42)")(value(23))
    value(23)
 
    >>> f(42)
    23
 
In the above, the ``just(arg)`` function is defined as being the same as its
argument. So, the ``"x==just(42)`` is treated as though you'd just said
``"x==42"``.
 
And, although we never defined an actual *implementation* of the ``just()``
function, it actually still works::
 
    >>> just(42)
    42
 
This is because if you decorate an empty function with ``@expand_as``, the
supplied condition will be compiled and attached to the existing function
object for you. (This saves you having to actually write the body.)
 
Of course, if you decorate, say, an already-existing function that you want
to replace, then nothing happens to that function::
 
    >>> def isint(ob):
    ... print "called!"
    ... return isinstance(ob, int)
 
    >>> expand_as("isinstance(x, int)")(isint)
    <function isint ...>
    
    >>> isint(42)
    called!
    True
 
But, the correct expansion still happens when you use that function in a rule::
 
    >>> around(f, "isint(x)")(value(99))
    value(99)
 
    >>> f(42)
    99
 
Note that it's ok to use ``let()`` or other binding-creating expressions inside
an expansion string, and they won't interfere with the surrounding conditions::
 
    >>> def oddment(a, b): pass
 
    >>> expand_as("let(x=a*2, y=x+b+1) and y")(oddment)
    <function oddment ...>
 
    >>> oddment(27, 51) # prove bindings work even in a function
    106
 
    >>> around(f, "x==oddment(27, 51) and x==106 and isint(x)")(value('yeah!'))
    value('yeah!')
 
    >>> f(106) # prove that x doesn't get redefined after oddment
    'yeah!'
 
In the above, temporary variables ``x`` and ``y`` are created in the
expansion, but they don't affect the original value of x in the rule where
the function is expanded.
 
Of course, this also means that you can't implement something like a
pattern-matching feature or the ``let()`` function using ``@expand_as``.
It's just an easier way to handle the sort of common cases where meta-functions
would be overkill.
 
 
Expression to Predicate Conversion
==================================

    
Okay, let's try out our new condition::
 
    >>> from peak.rules import value
 
    >>> def dummy(arg): return "default"
    >>> when(dummy, "arg==1 and priority(1)")(lambda arg: "1 @ 1")
    <function <lambda> ...>
    >>> when(dummy, "arg==1 and priority(1)")(value("1 @ 1"))
    value('1 @ 1')
 
    >>> dummy(1)
    '1 @ 1'
    >>> dummy(2)
    'default'
 
    >>> when(dummy, "arg==1 and priority(2)")(lambda arg: "1 @ 2")
    <function <lambda> ...>
    >>> when(dummy, "arg==1 and priority(2)")(value("1 @ 2"))
    value('1 @ 2')
 
    >>> dummy(1)
    '1 @ 2'

    'default'
 
 
    >>> when(dummy, "arg==2 and priority(2)")(lambda arg: "2 @ 2")
    <function <lambda> ...>
    >>> when(dummy, "arg==2 and priority(2)")(value("2 @ 2"))
    value('2 @ 2')
 
    >>> dummy(1)
    '1 @ 2'
    >>> dummy(2)
    '2 @ 2'
 
    >>> when(dummy, "arg==2 and priority(1)")(lambda arg: "2 @ 1")
    <function <lambda> ...>
    >>> when(dummy, "arg==2 and priority(1)")(value("2 @ 1"))
    value('2 @ 1')
 
    >>> dummy(1)
    '1 @ 2'
    >>> dummy(2)

to add the appropriate method(s) to ``type_to_test`` if you want it to also
work with the predicate engine.
 
So, let's test the actual upgrade process, and also confirm that you can
still pass in type tuples (or precomputed tests, signatures, etc.) after
upgrading::
 
    >>> def demo(ob): pass
    >>> tmp = when(demo, (int,))(value('int'))
    >>> tmp = when(demo, (str,))(value('str'))
 
    >>> demo(42)
    'int'
 
    >>> demo('test')
    'str'
 
    >>> tmp = when(demo, "ob in int and ob==42")(value('Ultimate answer'))
    >>> tmp = when(demo, (list,))(value('list'))
    >>> tmp = when(demo, Test(IsInstance(Local('ob')), Class(tuple)))(
    ... value('tuple')
    ... )
 
    >>> demo(42)
    'Ultimate answer'
 
    >>> demo([])
    'list'
 
    >>> demo(())
    'tuple'
 
    >>> demo('test'), demo(23)
    ('str', 'int')
 
And, just for the heck of it, let's make sure that you can upgrade to an
IndexedEngine by using any other values on a TypeEngine function::
 
    >>> def demo(ob): pass
    >>> tmp = when(demo, Test(IsInstance(Local('ob')), Class(tuple)))(
    ... value('tuple')
    ... )
 
    >>> demo(())
    'tuple'
 
 
 
Criterion Ordering
==================

 
    >>> def f(a,b): pass
    >>> f = abstract(f)
    >>> m = when(f, "isinstance(a, int) and a+b==42")(lambda a,b: None)
    >>> m = when(f, "isinstance(a, int) and a+b==42")(value(None))
    >>> engine = Dispatching(f).engine
    >>> list(Ordering(engine, IsInstance(Local('a'))).constraints)
    [frozenset([])]

    >>> def f(a,b): pass
    >>> f = abstract(f)
    >>> m = when(f, "isinstance(b, str) and a+b==42 and isinstance(a, int)")(
    ... lambda a,b: None
    ... value(None)
    ... )
    >>> engine = Dispatching(f).engine
    >>> list(Ordering(engine, IsInstance(Local('a'))).constraints)

    >>> def f(a,b): pass
    >>> f = abstract(f)
    >>> m = when(f, "isinstance(a, int) and isinstance(b, str) and a+b==42")(
    ... lambda a,b: None
    ... value(None)
    ... )
    >>> engine = Dispatching(f).engine
 

PythonPowered
ShowText of this page
EditText of this page
FindPage by browsing, title search , text search or an index
Or try one of these actions: AttachFile, DeletePage, LikePages, LocalSiteMap, SpellCheck