How To Freeze Some Arguments Over Multiple Related Class Methods
What's the 'best' method to take a collection of functions that use some common argument names (assumed to mean the same thing), and make an object that holds these functions, but
Solution 1:
This is an example of a class decorator that searches the class methods for wanted args and replaces the methods with their partialmethod versions. I am freezing the y
arg with value 2 to show also that it doesn't touch methods where y
is not used.
'''Freeze args in multiple functions wrapped as class methods,
using a class decorator'''
import math
from functools import partialmethod
import inspect
class Calc:
'''An imaginary Calc class with related methods that might share some args
between them'''
def add(self, x, y):
return x + y
def sub(self, x, y):
return x - y
def sqrt(self, x):
return math.sqrt(x)
def partial_cls_arg_pairs(cls, arg_pairs):
'''A class decorator to freeze arguments in class methods given
as an arg_pairs iterable of argnames with argvalues'''
cls_attrs = dict(cls.__dict__)
freezed_cls_attrs = dict()
for name, value in cls_attrs.items():
if inspect.isfunction(value):
for argname, argvalue in arg_pairs:
if argname in inspect.signature(value).parameters:
print('Freezing args in {}.'.format(name))
value = partialmethod(value, **{argname:argvalue})
freezed_cls_attrs[name] = value
return type(cls.__name__, (object,), freezed_cls_attrs)
c1 = Calc()
print(c1.add(1,2))
print(c1.sub(3,2))
print(c1.sqrt(2))
print()
CalcY2 = partial_cls_arg_pairs(Calc, [('y', 2)])
c2 = CalcY2()
print(c2.add(1))
print(c2.sub(3))
print(c2.sqrt(2))
Output:
3
1
1.4142135623730951
Freezing args in add.
Freezing args in sub.
3
1
1.4142135623730951
Post a Comment for "How To Freeze Some Arguments Over Multiple Related Class Methods"