some random reflections of a "Python newbie": (2) language issues

Tim Peters tim_one at email.msn.com
Thu Dec 9 22:19:00 EST 1999


[Alex Martelli]
> ...
> 4. why can't I overload "in" to have the
>     expected semantics and maybe be fast...?
>
> "if a in X:" and "for a in X:" will now both
> give errors unless X is a sequence.

"for a in X:" also works fine if X is an instance of a class that supports
the special __getitem__ method; see the docs; you are not required to look
at __getitem__'s index argument, and, indeed, it seems I don't more often
than I do.

"if a in X:" currently works only if X is a list, tuple or string.  In
Python 1.6 it's supposed to work too if X is an instance of a class that
supports the special __contains__ method; see the 1.6 docs, preferably after
they're written <wink>.

> ...
> The way I envision this -- if X chooses to
> implement a method __contains__, ...

Yup -- that's The Plan.

postcognitively y'rs  - tim






More information about the Python-list mailing list