Are decorators really that different from metaclasses...
anthonybaxter at gmail.com
Fri Aug 27 06:00:54 CEST 2004
On Thu, 26 Aug 2004 20:54:22 -0400, Paul Morrow <pm_mon at yahoo.com> wrote:
> Anthony Baxter wrote:
> Sure the interpreter uses __getitem__, but you use it too, right? I
> mean, you don't need the interpreter to tell you whether instances of
> the following class can act like a dictionary, do you?
> class Foo:
> def __getitem__(self, x): pass
Well, actually, no. The presence or absence of __getitem__ "tells" you nothing.
It depends on the implementation.
def __getitem__(self, key): raise AttributeError, '__getitem__'
> No you don't. Nor do you need to pretend that you're the interpreter,
> and simulate a call to an instance of Foo. That's because the mere
> presence of def __getitem__ tells you what you need to know. In this
> way, __getitem__ *does* serve as a declaration (of dictionary semantics)
> [*] to you and anyone reading your code.
No. It. Does. Not. "dictionary semantics" includes a hell of a lot
more than a "__getitem__". And list-like objects _also_ include a
> * But an implicit declaration of course. I guess the only way of
> *explicitly* stating that instances of a class can act like dictionaries
> is to have the class inherit from dict or UserDict.
Or use Interfaces. Or put something in the docstring.
> > class Foo:
> > def __init__(self):
> > self.d = dict(ape=False,spidermonkey=True)
> > def getMonkey(self, key):
> > return self.d[key]
> > def __getattr__(self, name):
> > if name == "__getitem__":
> > return self.getMonkey
> > else:
> > raise AttributeError, name
> > f = Foo()
> > print f['ape']
> > print f['spidermonkey']
> Now hold on just a minute. If I squint a little, I can still see
> __getitem__ in there somewhere.
As a *string*, buried away in the innards. So I make that string get
loaded from another object, or from a database, or whatever. Your
point is _wrong_. You cannot "declare" anything by simply the presence
or absence of magic double-under methods.
> Though I do believe that you are illustrating a good point; that you can
> mangle your code badly enough that it no longer lends itself to a
> declarative reading. And then, the only way for your poor reader to
> figure out what the heck it's doing is for him/her to act like the
> interpreter and walk through your code (or run it under the debugger).
Or read the docstring for the class.
Anthony, giving up.
More information about the Python-list