On Wed, 31 Jan 2001, Skip Montanaro wrote:
Ping> x is sequence-like if it provides __getitem__() but not keys()
So why does this barf?
>>> [].__getitem__
I was describing how to tell if instances are sequence-like. Before we get to make that judgement, first we have to look at the C method table. So: x is sequence-like if it has tp_as_sequence; all instances have tp_as_sequence; an instance is sequence-like if it has __getitem__() but not keys() x is mapping-like if it has tp_as_mapping; all instances have tp_as_mapping; an instance is mapping-like if it has both __getitem__() and keys() The "in" operator is implemented this way. x customizes "in" if it has sq_contains; all instances have sq_contains; an instance customizes "in" if it has __contains__() If sq_contains is missing, or if an instance has no __contains__ method, we supply the default behaviour by comparing the operand to each member of x in turn. This default behaviour is implemented twice: once in PyObject_Contains, and once in instance_contains. So i proposed this same structure for sq_iter and __iter__. x customizes "for ... in x" if it has sq_iter; all instances have sq_iter; an instance customizes "in" if it has __iter__() If sq_iter is missing, or if an instance has no __iter__ method, we supply the default behaviour by calling PyObject_GetItem on x and incrementing the index until IndexError. -- ?!ng "The only `intuitive' interface is the nipple. After that, it's all learned." -- Bruce Ediger, on user interfaces