[PEAK] PyProtocols: adapting None
Phillip J. Eby
pje at telecommunity.com
Thu Mar 30 13:08:34 EST 2006
At 07:28 PM 3/30/2006 +0200, Marko Mikulicic wrote:
>adapt could already return None if it is passed as the 'default'
>argument, so applications would be already prepared to obtain it as
>as an (possibly indirect) result of 'adapt'.
I'm saying that having a special AdaptedNone for this purpose is not
specified in the PEP, so anything that returns AdaptedNone isn't
necessarily usable with different PEP 246 implementations.
So, you'd have to lobby the PEP author before I'd be interested in changing
this, especially since the change isn't worth it for the use case, which
can be handled in other ways. For example, you can just define your
interface to have a method that returns the object to use. Then when you
adapt None to that interface, the adapter just has a method that returns
the adapted object.
Or, you can use RuleDispatch's generic functions, which in the simplest
case do exactly the same thing, but with less syntax:
import dispatch
@dispatch.on("ob")
def get_thing(ob):
"""Generic function for getting a thing"""
@get_thing.when([type(None), int, str])
def get_basic(ob):
return ob
@get_thing.when([SomeType,OtherType])
def get_other(ob):
# return whatever
Then 'get_thing(None)' will return None, and other things will do what you
define them to do.
In most cases, I've found that adaptation to very simple interfaces (e.g.
<2 methods or attrs) is usually better expressed as generic
functions. Which is why I created the generic function system in RuleDispatch.
For more of an introduction to generic functions, see:
http://peak.telecommunity.com/DevCenter/VisitorRevisited
>PyProtocols has already a difference between it and PEP 246.
>Code that raise TypeError to signal failure to adapt will not behave
>under PyPython like following strictly the PEP 246
>
>the documentation says:
>
><quote>
>These differences are the result of experience using the protocols
>package with PEAK, and advances in the Python state-of-the-art since
>PEP 246 was written (over two years ago). We believe that they make
>the adaptation protocol more robust, more predictable, and easier to
>use for its most common applications.
></quote>
Actually, I believe PEP 246 has been updated to include the PyProtocols
approach to handling TypeError.
More information about the PEAK
mailing list