Generate functions without closing in python

right now i am 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 user-class init method, which saves them as instance attributes. The disadvantage is that this makes class instances unmanaged. So I wonder if there is a way to create function generators by avoiding closures.

+6
source share
2 answers

You can use the class called:

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

Then, the closing state of your function is carried over instead of the instance attribute.

+8
source

Not that I recommend this for general use ... but there is an alternative approach to compiling and exec . It spawns a function without a closure.

 >>> def doit(constant): ... constant = "def constant(t):\n return %s" % constant ... return compile(constant, '<string>', 'exec') ... >>> exec doit(1) >>> constant(4) 1 >>> constant 

Note that for this, in the closing function or class (i.e. not in the global namespace), you must also pass exec to the corresponding namespace. See: https://docs.python.org/2/reference/simple_stmts.html#the-exec-statement

There is also a dual lambda approach, which is not really a closure, well, sort of ...

 >>> f = lambda x: lambda y:x >>> g = f(1) >>> g(4) 1 >>> import dill >>> _g = dill.dumps(g) >>> g_ = dill.loads(_g) >>> g_(5) 1 

You seemed to be worried about the ability to scatter objects like closures, so you can see that even double lambdas are legible if you use dill . The same goes for class instances.

0
source

All Articles