Exceptions, assigning a tuple

Erik Max Francis max at alcyone.com
Fri Nov 21 02:56:49 EST 2003


Derek Fountain wrote:

> OK, and what gives it that ability? I tried tuple(f), where f was a
> file
> object. It gave me the contents of the file! I tried it again on an
> instance of one of my own objects and got a "TypeError: iteration over
> non-sequence" exception.
> 
> It must be possible to give a class the ability to present itself as a
> tuple. How is that done?

The tuple function can work with instances which support an iterating
interface.  (This is why you were seeing this behavior with a file
object; iterating over a file object gives you the lines in sequence.)

>>> class C:
...  def __init__(self, x):
...   self.x = x
...  def __getitem__(self, i):
...   if i < self.x:
...    return i**2
...   else:
...    raise IndexError
... 
>>> c = C(10)
>>> tuple(c)
(0, 1, 4, 9, 16, 25, 36, 49, 64, 81)

-- 
   Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/
 __ San Jose, CA, USA && 37 20 N 121 53 W && &tSftDotIotE
/  \ 
\__/ Yes I'm / Learning from falling down / Heavily
    -- Lamya




More information about the Python-list mailing list