Using a dict as if it were a module namespace

Ross Ridge rridge at caffeine.csclub.uwaterloo.ca
Sun Jan 27 10:04:06 EST 2008


Steven D'Aprano writes:
>(1) Import the test and grab the values needed from it:
>
>    setup = """from __main__ import myfunc, test
>x, y = test['x'], test['y']"""
>
>
>I don't like this one. It doesn't seem very elegant to me, and it gets 
>unwieldy as the complexity increases. Every item I need from test has to 
>be named twice, violating the principle Don't Repeat Yourself. If the 
>tests change, the setup string has to be explicitly changed also. 

I think this is the way to go as it follows the principle of "say what
you mean."  You can however simplify it, and repeat yourself less,
by using the extended call syntax:

	expr = "myfunc(**test)"
	setup = """from __main__ import myfunc, test"""

...
>I don't like this one. It looks hackish, and I worry about conflicts and 
>side-effects. If it works (and I haven't tested it) it relies on an 
>implementation detail of timeit.Timer.__init__, namely the line
>"exec code in globals(), ns". Worst of all, it pollutes or even mangles 
>the global namespace of the calling code, not the code being tested.

It wouldn't work because the timeit module's "globals" are different
from the __main__ module's globals.

					Ross Ridge

-- 
 l/  //	  Ross Ridge -- The Great HTMU
[oo][oo]  rridge at csclub.uwaterloo.ca
-()-/()/  http://www.csclub.uwaterloo.ca/~rridge/ 
 db  //	  



More information about the Python-list mailing list