Status of PEP's?
Delaney, Timothy
tdelaney at avaya.com
Thu Feb 28 21:04:37 EST 2002
> From: Tim Peters [mailto:tim.one at comcast.net]
> [Delaney, Timothy]
> > ...
> > Are the following two equivalent though?
>
> Not necessarily, but the possible difference isn't where you think:
>
> > if 1 in obj:
> > pass
> >
> > if 1 in iter(obj):
> > pass
> >
> > i.e. is iter(obj) called implicitly in the first case?
>
> Maybe. First type(obj) is checked to see whether it
> implements __contains__
> (at the C level, whether obj->ob_type->tp_as_sequence->sq_contains is
> reachable and non-NULL). If it is, iter() gets involved if
> and only if the
> __contains__ method decides to use iter() (and, for example,
> dicts certainly
> do not). If type(obj) doesn't implement __contains__, then
> "in" tickles
> iter(obj) repeatedly.
That's pretty much what I thought - I was assuming the case that
__contains__ wasn't defined. It answers the real question, which was "In the
general case, is '1 in iterable' a valid expression?".
The answer is "Yes, but you can do something to prevent it."
Tim Delaney
More information about the Python-list
mailing list