[Python-3000] Abilities / Interfaces
sluggoster at gmail.com
Tue Nov 21 21:15:37 CET 2006
On 11/21/06, Guido van Rossum <guido at python.org> wrote:
> 2. More precise concepts. I'd like to distinguish between checking for
> abilities (which should be quick as it may be used many times during
> execution, e.g. whenever a generic function is called) and verifying
> an ability, which would entail checking the class to see whether it
> actually implements the API (and possibly maintains the invariants, if
> we go that route) stipulated by a claimed ability. It would be a
> performance nightmare if during he normal course of an application we
> would be *verifying* abilities over and over -- this is equivalent to
> a structural type check and can be very expensive. (Even more so if we
> have optional argument type declarations.)
If I understand correctly, checking for an ability means "Does class C
claim to have ability A?", analagous to isinstance(), and verifying an
ability means introspecting the class and inspecting its methods.
The distinction is similar to checking whether an XML document claims
to match a DTD (or just assuming it does), vs checking all the tags
and attributes against the DTD. The latter is definitely a lot of
overhead you don't need... except when you do.
> A Mapping must
> implement __getitem__() in a certain way. But does it need to
> implement __len__? get()? keys()? values() and items()?
Yes. And no. In other words, there should be at least two choices.
When most people think of "mapping" they expect x[key] to work. When
they think of "dict like" they may mean this, or they may want to also
call x.keys/values/items, and less commonly x.update and x.popitem.
Having two levels (Mapping and DictLike) would solve 90% of the
problem. Having three levels may be overkill. Same for lists, etc.
I wouldn't expect len(x) to work on every mapping. Maybe the mapping
models an external resource like a filesystem, and calculating the
length would be expensive. Maybe the object is volatile and doesn't
allow ascertaining all keys but only lookup of a particular key.
An example would be Cheetah's NameMapper. It looks up a variable
against a list of objects, examining each object's attributes and keys
at the current moment. Although it would be theoretically possible to
list all keys and calculate their number, this is not a supported
operation, and when you're recursing through 'self' and '__builtins__'
the number would become very large. The correct response to "Does
variable x exist?" is not "Is it in the list of existing keys?" but
"Does the NameMapper succeed in finding it?"
(As an aside, I got a momentary power outage while typing this, which
made me restart my computer. It reminded me that these things can
happen at any time.)
Mike Orr <sluggoster at gmail.com>
More information about the Python-3000