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

Steven D'Aprano steve+comp.lang.python at pearwood.info
Mon Jun 13 12:24:34 EDT 2011


Did you mean to cross-post this from python-ideas to python-list?

On Mon, 13 Jun 2011 16:43:11 +0100, MRAB wrote:

> Here's another way:
> 
> def do_work(args):
>      do_work.pr("doing spam")
>      spam()
>      do_work.pr("doing ham")
>      ham()
>      # and so on

Sure, there are lots of ways, but that has a number of serious 
disadvantages:

There's only one do_work.pr, which means you can't have two different 
pieces of code each calling do_work, one with verbose=true and the other 
with verbose=false. The pr attribute might be attached to the function 
object, but it suffers from the same "action-at-a-distance" faults as a 
global variable.

do_work.pr is not an optimization. You have to look up do_work in the 
global scope, then do another lookup in its namespace for .pr. Now I 
admit that for the specific example given, that's unlikely to be the 
bottleneck. But if you want to optimize name lookup, it has to be a local.



-- 
Steven



More information about the Python-list mailing list