[Python-ideas] 'Injecting' objects as function-local constants

Greg Ewing greg.ewing at canterbury.ac.nz
Tue Jun 14 01:29:40 CEST 2011


Steven D'Aprano wrote:

> Because you aren't monkey-patching the hook function (or, heaven help 
> us, monkey-patching builtins.print!) you don't need to fear 
> side-effects.

It's still rather non-obvious what's going on, though. Copious
commenting would be needed to make this style of coding
understandable.

Also, it doesn't seem to generalise. What if the function in
question calls other functions, which call other functions,
which themselves need a verbose option? It seems you would
need to explicitly wrap all the sub-function calls to pass
the hook on to them. And what if there is more than one
option to be hooked? You'd rapidly end up with a nightmarish
mess.

Here's another way to approach the problem:

   class HookableWorker(object):

     def hook(self, arg):
       pass

     def do_work(self):
       self.hook("Starting work")
       ...
       self.hook("Stopping work")

   def be_verbose(arg):
     print arg

   def main():
     worker = HookableWorker()
     if "--verbose" in sys.argv:
       worker.hook = be_verbose
     worker.do_work()

Now you can expand the HookableWorker class by adding more methods
that all share the same hook, still without anything being global.

-- 
Greg



More information about the Python-ideas mailing list