Skip to content

Commit 6c40635

Browse files
committed
Doctest for borg
1 parent 025f7cd commit 6c40635

File tree

1 file changed

+33
-32
lines changed

1 file changed

+33
-32
lines changed

patterns/creational/borg.py

Lines changed: 33 additions & 32 deletions
Original file line numberDiff line numberDiff line change
@@ -19,12 +19,6 @@
1919
added to the instance's attribute dictionary, but, since the attribute
2020
dictionary itself is shared (which is __shared_state), all other
2121
attributes will also be shared.
22-
For this reason, when the attribute self.state is modified using
23-
instance rm2, the value of self.state in instance rm1 also changes. The
24-
same happens if self.state is modified using rm3, which is an
25-
instance from a subclass.
26-
Notice that even though they share attributes, the instances are not
27-
the same, as seen by their ids.
2822
2923
*Where is the pattern used practically?
3024
Sharing state is useful in applications like managing database connections:
@@ -53,37 +47,44 @@ class YourBorg(Borg):
5347
pass
5448

5549

56-
if __name__ == '__main__':
57-
rm1 = Borg()
58-
rm2 = Borg()
50+
def main():
51+
"""
52+
>>> rm1 = Borg()
53+
>>> rm2 = Borg()
5954
60-
rm1.state = 'Idle'
61-
rm2.state = 'Running'
55+
>>> rm1.state = 'Idle'
56+
>>> rm2.state = 'Running'
6257
63-
print('rm1: {0}'.format(rm1))
64-
print('rm2: {0}'.format(rm2))
58+
>>> print('rm1: {0}'.format(rm1))
59+
rm1: Running
60+
>>> print('rm2: {0}'.format(rm2))
61+
rm2: Running
6562
66-
rm2.state = 'Zombie'
63+
# When the `state` attribute is modified from instance `rm2`,
64+
# the value of `state` in instance `rm1` also changes
65+
>>> rm2.state = 'Zombie'
6766
68-
print('rm1: {0}'.format(rm1))
69-
print('rm2: {0}'.format(rm2))
67+
>>> print('rm1: {0}'.format(rm1))
68+
rm1: Zombie
69+
>>> print('rm2: {0}'.format(rm2))
70+
rm2: Zombie
7071
71-
print('rm1 id: {0}'.format(id(rm1)))
72-
print('rm2 id: {0}'.format(id(rm2)))
72+
# Even though `rm1` and `rm2` share attributes, the instances are not the same
73+
>>> rm1 is rm2
74+
False
7375
74-
rm3 = YourBorg()
76+
# Shared state is also modified from a subclass instance `rm3`
77+
>>> rm3 = YourBorg()
7578
76-
print('rm1: {0}'.format(rm1))
77-
print('rm2: {0}'.format(rm2))
78-
print('rm3: {0}'.format(rm3))
79+
>>> print('rm1: {0}'.format(rm1))
80+
rm1: Init
81+
>>> print('rm2: {0}'.format(rm2))
82+
rm2: Init
83+
>>> print('rm3: {0}'.format(rm3))
84+
rm3: Init
85+
"""
7986

80-
### OUTPUT ###
81-
# rm1: Running
82-
# rm2: Running
83-
# rm1: Zombie
84-
# rm2: Zombie
85-
# rm1 id: 140732837899224
86-
# rm2 id: 140732837899296
87-
# rm1: Init
88-
# rm2: Init
89-
# rm3: Init
87+
88+
if __name__ == "__main__":
89+
import doctest
90+
doctest.testmod()

0 commit comments

Comments
 (0)