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

Steven D'Aprano steve at pearwood.info
Tue Jun 14 01:25:52 CEST 2011


Terry Reedy wrote:
[...]
> if __name__ == '__main__':
>     if '--verbose' in sys.argv:
>         wrap = inject(hook=print)
> 
> I do not see the point of all this complication. If you are not trying 
> to optimize the function (and adding such hooks is obviously not),
>         hook = print
> works just fine (in 3.x ;-).


You're modifying a global variable. Now any other function that calls 
do_work() for its own purposes suddenly finds it mysteriously printing. 
A classic action-at-a-distance bug. For a simple stand-alone script, 
there's no problem, but once you have more complexity in your app, or a 
library, things become very different.

My apologies, I've been doing a lot of reading about the pros and cons 
(mostly cons *wink*) of monkey-patching in the Ruby world, the 
open/closed principle, and various forms of bugs caused by the use of 
globals. I assumed that the problems would be blindingly obvious. I 
suppose they were only obvious to me because I'd just immersed myself in 
them for the last day or so!


-- 
Steven




More information about the Python-ideas mailing list