[Python-ideas] A "within" keyword
steve at pearwood.info
Sat Jun 9 04:21:23 EDT 2018
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 : import types
> In : ns = types.SimpleNamespace(a=1)
> In : eval('a', ns.__dict__)
> Out: 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.
More information about the Python-ideas