Using a dict as if it were a module namespace

Steven Bethard steven.bethard at gmail.com
Sun Jan 27 13:16:00 EST 2008


Steven D'Aprano wrote:
> I have a problem which I think could be solved by using a dict as a 
> namespace, in a similar way that exec and eval do.
> 
> When using the timeit module, it is very inconvenient to have to define 
> functions as strings. A good alternative is to create the function as 
> normal, and import it:
> 
> def myfunc(x, y):
>     return x+y
> 
> timeit.Timer("myfunc(59, 60)", "from __main__ import myfunc").timeit()
> 
> 
> Not only is this an easy idiom to follow, but myfunc can live in another 
> module: just replace __main__ with the module name.
> 
> Now, I'm trying to build a suite of tests to use with timeit. I have a 
> bunch of tests which I've created as dicts:
> 
> test_suite= [dict(x=59, y=60), dict(x=-1, y=-2)]
> 
> What I *think* I want to do is use the from ... import idiom to grab 
> arguments from the dicts as if they were modules, but this doesn't work:
> 
> expr = "myfunc(x, y)"
> for test in test_suite:
>     setup = "from __main__ import myfunc; from test import x, y"
>     t = timeit.Timer(expr, setup).timeit()
[snip]
> (2) Mess with the global namespace:
> 
>     globals().update(t)
>     setup = "from __main__ import myfunc"

Why not mess with the namespace inside the setup code? E.g.::

     >>> test_suite = [dict(x=59, y=60), dict(x=-1, y=-2)]
     >>> expr = "myfunc(x, y)"
     >>> for test in test_suite:
     ...     setup = textwrap.dedent('''
     ...     from __main__ import myfunc, test
     ...     globals().update(test)''')
     ...     t = timeit.Timer(expr, setup).timeit()
     ...

That shouldn't pollute your actual namespace::

     >>> x
     Traceback (most recent call last):
       File "<interactive input>", line 1, in <module>
     NameError: name 'x' is not defined
     >>> y
     Traceback (most recent call last):
       File "<interactive input>", line 1, in <module>
     NameError: name 'y' is not defined

STeVe



More information about the Python-list mailing list