1 class NamedNumbers(object):
2 """Base for Enum and Flags."""
4 def __init__(self
, value
):
8 >>> n = NamedNumbers(42)
15 class Enum(NamedNumbers
):
34 for n
, v
in self
.__class
__.__dict
__.iteritems():
37 return str(self
.value
)
40 class Flags(NamedNumbers
):
45 >>> class MyFlags(Flags):
57 >>> str(MyFlags(9)) # doctest: +SKIP
62 for n
, v
in self
.__class
__.__dict
__.iteritems():
63 if isinstance(v
, int): # FIXME long
64 if self
.value
& v
or (self
.value
== 0 and v
== 0):
67 names
= [has
[v
] for v
in sorted(has
.keys())]
68 # TODO unknown values?
69 return ",".join(names
)
74 >>> t = Table("A", "Bee", "C")
76 >>> t.row("ay", "B", "sea")
78 >>> t.row("", "b", "c")
86 >>> Table.terse = True
92 # there are trailing spaces in the above non-terse printout
95 "No headings and no padding, suitable for parsing."
97 def __init__(self
, *args
):
98 "The arguments are column headings."
104 def from_items(obj
, *items
):
105 t
= Table("Property", "Value")
111 def from_nested_dict(dd
):
112 t
= Table("Section", "Property", "Value")
113 for s
, d
in dd
.iteritems():
115 for k
, v
in d
.iteritems():
116 if isinstance(v
, list):
121 def row(self
, *args
):
122 """The arguments are row items.
124 str is applied to them"""
125 self
.rows
.append(map(str,args
))
128 def pad_row(row
, col_sizes
):
129 return map(str.ljust
, row
, col_sizes
)
131 def col_widths(self
):
132 "Returns a list of the column widths."
134 # the table of lengths of original items
135 lengths
= map(lambda cells
: map(len, cells
), self
.rows
+ [self
.headings
])
136 return reduce(lambda cells1
, cells2
: map(max, cells1
, cells2
), lengths
)
139 "Formats the table, tersely."
141 rs
= map("|".join
, self
.rows
)
148 return self
.terse_str()
150 cw
= self
.col_widths()
152 return " | ".join(self
.pad_row(items
, cw
))
153 h
= fmt_row(self
.headings
)
154 s
= "-+-".join(map(lambda w
: "-" * w
, cw
))
155 rs
= map(fmt_row
, self
.rows
)
161 if __name__
== "__main__":