pindakaas pindakaas - 29 days ago 15
Python Question

Freezing Function Arguments

I am trying to write a class that gives the functionality of the input function, but remembers the arguments from last call and will only update them like a dictionary. I have this so far but I would love to know if there is a better way:

class freezefunc:
def __init__(self, func, **funcargs):
self.func = func
self.funcargs = {}

def call(self, **kwargs):
self.funcargs.update(kwargs)
self.func(**self.funcargs)


So this works like this then:

def func(a):
print a
frozenfunc = freezefunc(func)
frozenfunc.call(a='somevalue')


prints: somevalue

frozenfunc.call(a='theupdatedvalue')


prints: theupdatedvalue

Is there something like this that I just haven't found?

UPDATDE: the function partial from the library functools performs very much the same task.

Answer

The special method __call__ lets you call frozenfunc, directly:

class freezefunc:
    def __init__(self, func, **funcargs):
        self.func = func
        self.funcargs = {}

    def __call__(self, **kwargs):
        self.funcargs.update(kwargs)
        return self.func(**self.funcargs)

def func(a):
    print(a)

Now:

frozenfunc = freezefunc(func)
frozenfunc(a='somevalue')

prints:

somevalue

and:

frozenfunc(a='theupdatedvalue')

prints:

theupdatedvalue