Skip to content

Commit 8b23f0a

Browse files
committed
-
1 parent 8d62af8 commit 8b23f0a

File tree

2 files changed

+58
-5
lines changed

2 files changed

+58
-5
lines changed

source_py3/python_toolbox/monkeypatching_tools.py

Lines changed: 8 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@
1212

1313

1414
@decorator_tools.helpful_decorator_builder
15-
def monkeypatch_method(monkeypatchee, name=None):
15+
def monkeypatch_method(monkeypatchee, name=None, override_if_exists=True):
1616
'''
1717
Monkeypatch a method into a class (or an object).
1818
@@ -48,8 +48,8 @@ def decorator(function):
4848

4949
new_method = function if monkeypatchee_is_a_class else \
5050
types.MethodType(function, class_of_monkeypatchee)
51-
setattr(monkeypatchee, name_, new_method)
52-
return function
51+
setattr_value = new_method
52+
return_value = function
5353
else:
5454
# `function` is probably some kind of descriptor.
5555
if not monkeypatchee_is_a_class:
@@ -76,8 +76,11 @@ def decorator(function):
7676
)
7777
# #
7878
### Finished getting name of descriptor. ######################
79-
setattr(monkeypatchee, name_, function)
80-
return function
79+
setattr_value = return_value = function
80+
81+
if override_if_exists or not hasattr(monkeypatchee, name_):
82+
setattr(monkeypatchee, name_, setattr_value)
83+
return return_value
8184

8285
return decorator
8386

source_py3/test_python_toolbox/test_monkeypatching_tools.py

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,31 @@ def __eq__(self, other):
2222
return self is other
2323

2424

25+
def test():
26+
'''Test basic workings of `monkeypatch_method`.'''
27+
28+
class A(EqualByIdentity):
29+
pass
30+
31+
@monkeypatching_tools.monkeypatch_method(A)
32+
def meow(a):
33+
return (a, 1)
34+
35+
a = A()
36+
37+
assert a.meow() == meow(a) == (a, 1)
38+
39+
@monkeypatching_tools.monkeypatch_method(A, 'roar')
40+
def woof(a):
41+
return (a, 2)
42+
43+
assert a.roar() == woof(a) == (a, 2)
44+
45+
assert not hasattr(a, 'woof')
46+
47+
del meow, woof
48+
49+
2550
def test():
2651
'''Test basic workings of `monkeypatch_method`.'''
2752

@@ -47,6 +72,31 @@ def woof(a):
4772
del meow, woof
4873

4974

75+
def test_without_override():
76+
77+
class A(EqualByIdentity):
78+
def booga(self):
79+
return 'Old method'
80+
81+
@monkeypatching_tools.monkeypatch_method(A, override_if_exists=False)
82+
def meow(a):
83+
return (a, 1)
84+
85+
a = A()
86+
87+
assert a.meow() == meow(a) == (a, 1)
88+
89+
90+
@monkeypatching_tools.monkeypatch_method(A, override_if_exists=False)
91+
def booga():
92+
raise RuntimeError('Should never be called.')
93+
94+
a = A()
95+
96+
assert a.booga() == 'Old method'
97+
98+
99+
50100
def test_monkeypatch_property():
51101

52102
class A(EqualByIdentity):

0 commit comments

Comments
 (0)