Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generate functions without closures in python

right now I'm using closures to generate functions like in this simplified example:

def constant_function(constant):
    def dummyfunction(t):
        return constant
    return dummyfunction

These generated functions are then passed to the init-method of a custom class which stores them as instance attributes. The disadvantage is that that makes the class-instances unpickleable. So I'm wondering if there is a way to create function generators avoiding closures.

like image 353
jan Avatar asked Feb 22 '13 16:02

jan


1 Answers

You could use a callable class:

class ConstantFunction(object):
    def __init__(self, constant):
        self.constant = constant
    def __call__(self, t):
        return self.constant

def constant_function(constant):
    return ConstantFunction(constant)

The closure state of your function is then transferred to an instance attribute instead.

like image 146
Martijn Pieters Avatar answered Sep 20 '22 12:09

Martijn Pieters