Skip to content

Commit a06e05f

Browse files
committed
-
1 parent 8b23f0a commit a06e05f

File tree

1 file changed

+26
-0
lines changed

1 file changed

+26
-0
lines changed

source_py3/python_toolbox/monkeypatching_tools.py

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,9 +4,11 @@
44
'''Tools for monkeypatching.'''
55

66
import sys
7+
import inspect
78
import types
89

910
from python_toolbox import misc_tools
11+
from python_toolbox import dict_tools
1012
from python_toolbox import decorator_tools
1113
from python_toolbox import caching
1214

@@ -84,3 +86,27 @@ def decorator(function):
8486

8587
return decorator
8688

89+
90+
def change_defaults(function, new_defaults={}):
91+
def change_defaults_(function_, new_defaults_):
92+
signature = inspect.Signature.from_function(function_)
93+
defaults = list(function_.__defaults__)
94+
defaultful_parameters = dict_tools.filter_items(
95+
signature.parameters,
96+
lambda name, parameter: parameter.default != inspect._empty
97+
)
98+
for i, (name, parameter) in enumerate(defaultful_parameters):
99+
if name in new_defaults_:
100+
defaults[i] = new_defaults[name]
101+
102+
if not callable(function) and new_defaults == {}:
103+
# Decorator mode:
104+
actual_new_defaults = function
105+
return lambda function_: change_defaults_(function_,
106+
actual_new_defaults)
107+
else:
108+
# Normal usage mode:
109+
change_defaults(function, new_defaults)
110+
111+
112+

0 commit comments

Comments
 (0)