On Fri, Jun 08, 2018 at 03:07:28PM -0700, Michael Selik wrote:

> You can use ``eval`` to run an expression, swapping in a different globals
> and/or locals namespace. Will this serve your purpose?
> 
> In [1]: import types
> In [2]: ns = types.SimpleNamespace(a=1)
> In [3]: eval('a', ns.__dict__)
> Out[3]: 1

The public API for getting an object namespace is vars(ns).

But why would we write eval('a', vars(ns)) instead of getattr(ns, 'a') 
or even better just ns.a? Is your Python code too fast and you need to 
slow it down? *wink*

eval and exec are useful when the code you want to run needs to be 
constructed at runtime. Its not generally useful when you know what you 
want ahead of time as in your example above.



-- 
Steve
_______________________________________________
Python-ideas mailing list
Python-ideas@python.org
https://mail.python.org/mailman/listinfo/python-ideas
Code of Conduct: http://python.org/psf/codeofconduct/

Reply via email to