
On Mon, Jun 13, 2011 at 5:33 PM, Steven D'Aprano <steve@pearwood.info> wrote:
def hook(*args): pass
def do_work(args): hook("doing spam") spam() hook("doing ham") ham() # and so on
if __name__ == '__main__': if '--verbose' in sys.argv: wrap = inject(hook=print) else: wrap = lambda func: func # do nothing # or `inject(hook=hook)` to micro-optimize wrap(do_work)(my_arguments)
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 super_freezer.apply(sys.modules) 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 functions. Thoughts? -- Paul