-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathduck_punch.py
48 lines (37 loc) · 880 Bytes
/
duck_punch.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
import sys
class Something:
'''A class with a method to write'''
def __init__(self):
self.foo = 333
def write(self, outfile):
outfile.write('{}\n'.format(self.foo))
# Pretend this is a file
output_file = sys.stdout
# Instantiate Something and write. All is well
s = Something()
s.write(output_file)
def save_obj_to_output(obj, output):
...
obj.save(output)
...
try:
save_obj_to_output(s, output_file)
except AttributeError:
print('oopsie')
else:
print('woohoo')
## What to do?
import types
# Use the types module
# Duck punch
def duck_punch_save(self, output_file):
self.write(output_file)
# Add a new method after instantiation :D
s.save = types.MethodType(duck_punch_save, s)
# Now does this work?
try:
save_obj_to_output(s, output_file)
except AttributeError:
print('oopsie')
else:
print('woohoo')