[Python-3000] iostack and Oh Oh (original) (raw)

Josiah Carlson jcarlson at uci.edu
Sat Dec 9 18:53:34 CET 2006


"Steven Bethard" <steven.bethard at gmail.com> wrote:

On 12/9/06, Josiah Carlson <jcarlson at uci.edu> wrote: > I'd prefer to see... > > class MyMapping: > @implements(mapping) > def getitem(self, key): > ... > > @implements(mapping) > def len(self): > ... > [snip] > > P.S. Here's a 10 minute implementation of the above semantics that is > almost backwards compatible with Python 2.3 (except for the decorator > thing, which Python 2.3 has to do without). [snip] > builtins.type = type

Sorry, I don't understand this implementation. I just tried it and the following fails because _getitem_ is now an implementswrapper that accepts the wrong arguments:: class C(object): @implements(mapping) def getitem(self, item): return 42 C()[1]

It doesn't work because we need to replace the base metaclass from object, which the above mechanism doesn't do. It half-asses it by monkey-patching builtins, but object.new doesn't look in builtins, it uses CPython calls.

If you want to get your above use to work all the time (I believe, I hadn't tested it), you can also add the following just after the builtins.type = type .

class object(object):
    __metaclass__ = type

__builtins__.object = object

But I think the implements() decorator is a good way to approach this. Here's a different approach to it::

[snip]

class C(object): metaclass = interfacemonitor

@implements(Mapping) def getitem(self, key): return 4 @implements(Mapping) def iter(self): return [4, 4, 4] Note that with this code, an interface is just a set of methods, so you can use supports() equally well to check for support of individual methods or to check support for whole sets of methods.

That's what I was getting at with the previous version, though instead of using methods on the various interface objects (eg Mapping), I used objects in the class namespace. Using a function does allow for doing argument list length and/or keyword name verification, but I don't know if we want to go that far.

Using the monkey patching of builtins.object as I include in this message, makes the metaclass bit that you use unnecessary.

I also have a personal aversion for adding yet another attribute to the methods that implement interfaces, but since we are adding signature, etc., and no one else seems to be complaining, what's one more?



More information about the Python-3000 mailing list