[Python-Dev] RE: PySequence_Contains (original) (raw)

Guido van Rossum guido@digicool.com
Sat, 05 May 2001 17:31:05 -0500


[Guido] > Actually, instancecontains checks for AttributeError only after > calling instancegetattr(), whose only purpose is to return the > requested attribute or raise AttributeError, so here it is safe: the > contains function hasn't been called yet.

[Tim]

I'd say "safer", but not "safe": at that point we only know that some attribute didn't exist, somewhere, while attempting to look up "contains". Ignoring it could, e.g., be masking a bug in a getattr hook, like

def getattr(self, attr): return globalresolver.resolve(self, attr) where globalresolver has lost its "resolve" attr. "except" clauses aren't more bulletproof in C than in Python <0.9 wink>.

Yes, but attribute errors inside getattr hooks are always a problem to debug, since raising AttributeError is part of its job. So this is not new. I should have said "as safe as it gets."

> With previous behavior of 'x in instance'. Before we had > contains, 'x in y' always iterated over the items of y as a > sequence, comparing them to x one at a time.

I don't believe I ever knew that! Thanks. I erronesouly assumed that the looping behavior was introduced when contains was added.

Surely you knew that "x in y" looped over the items of y? What else could it have done? It was only defined on sequences!

> ... > No, that was probably just an oversight -- clearly it should have used > rich comparisons. (I guess this is a disadvantage of the approach I'm > recommending here: if the default behavior changes, the > reimplementation of the default behavior in the class must be changed > too.)

I factored out the new iterator-based contains logic into a new private API function, called when appropriate by both PySequenceContains() and instancecontains(). So any future changes to what iterator-based contains means will only need to be made in one place.

Cool.

--Guido van Rossum (home page: http://www.python.org/~guido/)