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')
52 r"""as_tuple(obj) -> tuple :: Convert objects to tuple.
54 This function returns a tuple for any object. If the object is
55 a string or any non-sequence object, it returns a tuple with the
56 single value. If the object is a sequece or a generator, it returns
57 the conversion to a tuple of it.
65 >>> print f([[1,2,3],[6,7,8]])
66 ([1, 2, 3], [6, 7, 8])
67 >>> print f(dict(a=1, b=2))
70 if isinstance(obj, basestring):
72 if hasattr(obj, 'items'):
73 return tuple(obj.items())
74 if hasattr(obj, '__iter__'):
79 r"""as_table(obj) -> tuple of tuples :: Convert objects to tuple of tuples.
81 This function returns a tuple of tuples for any object.
89 >>> print f([[1,2,3],[6,7,8]])
90 ([1, 2, 3], [6, 7, 8])
91 >>> print f(dict(a=1, b=2))
96 if isinstance(i, basestring):
98 if hasattr(i, '__iter__'):
102 return ((),) # empty table
105 if __name__ == '__main__':
112 return (self.a, self.b)
123 for f in (as_tuple, as_table):
133 print f([[1,2,3],[6,7,8]])
137 print f(dict(a=1, b=2))