[Tutor] Test Question

Steven D'Aprano steve at pearwood.info
Mon Jul 1 15:40:43 CEST 2013


On 01/07/13 19:58, John Steedman wrote:
> Good morning all,
>
> A question that I am unsure about.  I THINK I have the basics, but I am not
> sure and remain curious.
>
> 1. What does this mean?
>>>> if my_object in my_sequence:
> ...


Others have already answered this, but for completion, it is testing whether "my_object" can be found as an element of the sequence, iterable, or container "my_sequence".


> 2. What can go wrong with this? What should a code review pick up on?

Depends on context. Without context, nearly anything could go wrong:

NameError -- perhaps one or both of the names are undefined;

TypeError -- perhaps the names are misleading, and my_sequence is not a sequence at all;

Perhaps my_sequence is an infinite iterator and the above will never complete;

etc.

> I believe that "my_sequence" might be a either container class or a
> sequence type. An effective __hash__ function would be required for each
> "my_object".

Correct, if my_sequence is in fact a dict or other mapping that relies on hashing.

But in fact it's not just the presence of a __hash__ method on my_object which is required, but that the __hash__ method can actually return. E.g. tuples have a __hash__ method, but that relies on every element of the tuple being hashable:

py> (1, 2, 3) in {}
False
py> (1, 2, [3]) in {}
Traceback (most recent call last):
   File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'list'


> I HTINK you'd need to avoid using floating point variables
> that might round incorrectly.

No, Python floats are not rounded when doing containment testing. They may have been rounded earlier, but `x in container` will use the full precision of the float.


> Are there other issues?

Nothing obvious to me.




-- 
Steven


More information about the Tutor mailing list