1 # vim: set encoding=utf-8 et sw=4 sts=4 :
6 This module provides some tools to ease working with sequences.
10 r"""Sequence() -> Sequence instance.
12 This is an abstract class to ease the implementation of sequences. You can
13 inherit your objects from this class and implement just a method called
14 as_tuple() which returns a tuple representation of the object.
18 >>> class A(Sequence):
19 >>> def __init__(self):
22 >>> def as_tuple(self):
23 >>> return (self.a, self.b)
30 r"iter(obj) -> iterator object :: Get iterator."
31 for i in self.as_tuple():
35 r"len(obj) -> int :: Get object length."
36 return len(self.as_tuple())
38 def __getitem__(self, i):
39 r"obj[i] -> object :: Get item with the index i."
40 return self.as_tuple()[i]
42 def __unicode__(self):
43 return u'%s%r' % (self.__class__.__name__, self.as_tuple())
46 return unicode(self).encode('utf-8')
51 def __cmp__(self, other):
52 return cmp(self.as_tuple(), other.as_tuple())
55 r"""as_tuple(obj) -> tuple :: Convert objects to tuple.
57 This function returns a tuple for any object. If the object is
58 a string or any non-sequence object, it returns a tuple with the
59 single value. If the object is a sequece or a generator, it returns
60 the conversion to a tuple of it.
68 >>> print f([[1,2,3],[6,7,8]])
69 ([1, 2, 3], [6, 7, 8])
70 >>> print f(dict(a=1, b=2))
73 if isinstance(obj, basestring):
75 if hasattr(obj, 'items'):
76 return tuple(obj.items())
77 if hasattr(obj, '__iter__'):
82 r"""as_table(obj) -> tuple of tuples :: Convert objects to tuple of tuples.
84 This function returns a tuple of tuples for any object.
92 >>> print f([[1,2,3],[6,7,8]])
93 ([1, 2, 3], [6, 7, 8])
94 >>> print f(dict(a=1, b=2))
99 if isinstance(i, basestring):
101 if hasattr(i, '__iter__'):
105 return ((),) # empty table
108 if __name__ == '__main__':
115 return (self.a, self.b)
126 for f in (as_tuple, as_table):
136 print f([[1,2,3],[6,7,8]])
140 print f(dict(a=1, b=2))