Skip to content Skip to sidebar Skip to footer

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

classCalc:
    '''An imaginary Calc class with related methods that might share some args
    between them'''defadd(self, x, y):
        return x + y
    defsub(self, x, y):
        return x - y
    defsqrt(self, x):
        return math.sqrt(x)

defpartial_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

    returntype(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:

311.4142135623730951

Freezing args inadd.
Freezing args in sub.
311.4142135623730951

Post a Comment for "How To Freeze Some Arguments Over Multiple Related Class Methods"