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]
43 return '%s%r' % (self.__class__.__name__, self.as_tuple())
46 r"""as_tuple(obj) -> tuple :: Convert objects to tuple.
48 This function returns a tuple for any object. If the object is
49 a string or any non-sequence object, it returns a tuple with the
50 single value. If the object is a sequece or a generator, it returns
51 the conversion to a tuple of it.
59 >>> print f([[1,2,3],[6,7,8]])
60 ([1, 2, 3], [6, 7, 8])
61 >>> print f(dict(a=1, b=2))
64 if isinstance(obj, basestring):
66 if hasattr(obj, 'items'):
67 return tuple(obj.items())
68 if hasattr(obj, '__iter__'):
73 r"""as_table(obj) -> tuple of tuples :: Convert objects to tuple of tuples.
75 This function returns a tuple of tuples for any object.
83 >>> print f([[1,2,3],[6,7,8]])
84 ([1, 2, 3], [6, 7, 8])
85 >>> print f(dict(a=1, b=2))
90 if isinstance(i, basestring):
92 if hasattr(i, '__iter__'):
96 return ((),) # empty table
99 if __name__ == '__main__':
106 return (self.a, self.b)
117 for f in (as_tuple, as_table):
127 print f([[1,2,3],[6,7,8]])
131 print f(dict(a=1, b=2))