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.
source share