[Python-ideas] 'Injecting' objects as function-local constants
paul at colomiets.name
Mon Jun 13 21:14:31 CEST 2011
On Mon, Jun 13, 2011 at 5:33 PM, Steven D'Aprano <steve at pearwood.info> wrote:
> def hook(*args):
> def do_work(args):
> hook("doing spam")
> hook("doing ham")
> # and so on
> if __name__ == '__main__':
> if '--verbose' in sys.argv:
> wrap = inject(hook=print)
> wrap = lambda func: func # do nothing
> # or `inject(hook=hook)` to micro-optimize
> If you want to add logging, its easy: just add an elif clause with
> wrap = inject(hook=logger).
It's quite promising idea.
Currenlty there are notion of cell for closures. What if globals would also
use a cell? So that cell cound be either bound to a value or to a name
in globals or builtin dictionary. With this in mind it could be
possible to either
change binding from name to value or vice versa, our to make a copy of the
function with another cells.
I think this adheres to Python philosophy of having anything modifyable.
It will add at most two words of memory for each cell (name and global dict),
and probably will not make interpreter slower. Also will probably
allow to remove
__globals__ attribute from functions in the long term.
Then it even be possible to make some modules faster by either
from __future__ import fast_bindings
or it could be done by some external library like:
__super_freezer_allow__ = True
import sys, super_freezer
Probably about 80% modules do not need to rebind globals, so they
can run faster. And if you need to monkeypatch them, just either
not freeze globals in this module or change the bindings in all its
More information about the Python-ideas