Skip to content

Commit 4445c40

Browse files
committed
Cleaned up networkmanager.util.
Added docstrings with doctest. Enum returns str(value) instead of "?" for unknown values. Flags translates 0 to its name.
1 parent 9652b89 commit 4445c40

File tree

1 file changed

+52
-13
lines changed

1 file changed

+52
-13
lines changed

networkmanager/util.py

Lines changed: 52 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1,34 +1,73 @@
11
class NamedNumbers:
2+
"""Base for Enum and Flags."""
3+
24
def __init__(self, value):
35
self.value = value
46
def __int__(self):
7+
"""
8+
>>> n = NamedNumbers(42)
9+
10+
>>> int(n)
11+
42
12+
"""
513
return self.value
614

715
class Enum(NamedNumbers):
8-
"""enum
9-
10-
class Foo(Enum):
11-
FOO=1
12-
BAR=2
16+
"""Enumeration."""
1317

14-
>>> e = Foo(Foo.BAR)
15-
>>> str(e)
16-
"BAR"
17-
"""
1818
def __str__(self):
19+
"""
20+
>>> class Foo(Enum):
21+
... ONE = 1
22+
... TWO = 2
23+
24+
>>> Foo.ONE
25+
1
26+
27+
>>> str(Foo(Foo.TWO))
28+
'TWO'
29+
30+
>>> str(Foo(3))
31+
'3'
32+
"""
33+
1934
for n, v in self.__class__.__dict__.iteritems():
2035
if v == self.value:
2136
return n
22-
return "?"
37+
return str(self.value)
2338
# TODO __repr__
2439

2540
class Flags(NamedNumbers):
41+
"""Bit flags."""
42+
2643
def __str__(self):
44+
"""
45+
>>> class MyFlags(Flags):
46+
... NONE = 0x0
47+
... EXECUTE = 0x1
48+
... WRITE = 0x2
49+
... READ = 0x4
50+
51+
>>> str(MyFlags(5))
52+
'EXECUTE,READ'
53+
54+
>>> str(MyFlags(0))
55+
'NONE'
56+
57+
>>> str(MyFlags(9)) # doctest: +SKIP
58+
'EXECUTE,0x8'
59+
"""
60+
2761
has = {}
2862
for n, v in self.__class__.__dict__.iteritems():
29-
if isinstance(v, int) and self.value & v: # FIXME long
30-
has[v] = n
63+
if isinstance(v, int): # FIXME long
64+
if self.value & v or (self.value == 0 and v == 0):
65+
has[v] = n
66+
3167
names = [has[v] for v in sorted(has.keys())]
32-
# TODO zero is a special case
3368
# TODO unknown values?
3469
return ",".join(names)
70+
71+
if __name__ == "__main__":
72+
import doctest
73+
doctest.testmod()

0 commit comments

Comments
 (0)