[Tutor] What's in a name?

spir denis.spir at gmail.com
Sat Jan 4 11:51:37 CET 2014


On 01/04/2014 06:32 AM, Keith Winston wrote:
> On Fri, Jan 3, 2014 at 11:59 PM, Steven D'Aprano <steve at pearwood.info>wrote:
>
>> thelist = vars()[name]
>
>
>
> I see: vars() certainly looks less dangerous than eval(), but I'm guessing
> that's still smelly code? I hadn't known about vars() or I probably would
> have used it.

It is not as much smelly as somewhat "meta". It talks about Python's own 
conception, here about scopes (or namespaces). [I will let so-called 
"non-locals" aside, for simplicity.] Imagine that Python provided 2 dicts, 
always there:
* top_vars, for vars defined at top module level (included imports)
* local_vars for function local vars (included inputs)
Then, you could write:

a = 1
def f ():
     top_vars.a   = 2	# redef / change symbol a
     local_vars.b = 1	# def / create symbol b
     print(top_vars.a, local_vars.b)

which is the same as actual Python code:

a = 1
def f ():
     global a
     a = 2
     b = 1
     print(a, b)

but shows more or less how things work behind the stage.

local() and globals() return a dict equivalent to my imaginary local_vars and 
global_vars, resp. [But in the actual implementation, things are somewhat more 
low-level for efficiency; esp. IIRC locals are not truely named if you don't ask 
for them, as in most dynamic langs; but I may be wrong]. If Python scope were 
simply, truely, directly Python data (dicts), without the need to call a 
function that fabricates the dict on need, then the language would be 
"homoiconic" (on this aspect of its functioning), which just means that it works 
using its own data (types). Thus, the "meta" view.

vars() is somewhat special, works for any namespace-like component. See:
http://docs.python.org/3/library/functions.html
for a few details.

Denis




More information about the Tutor mailing list