Question about locals()

Steven D'Aprano steven at REMOVE.THIS.cybersource.com.au
Tue May 19 02:06:23 EDT 2009


Sorry for breaking threading, the original post is not being carried by 
my ISP. 


On Tue, 19 May 2009, Gökhan SEVER wrote:
> Hello,
>
> Could you please explain why locals() allow me to create variables that
> are not legal in Python syntax. Example: locals()['1abc'] = 55. Calling
> of 1abc results with a syntax error. Shouldn't it be better to raise an
> error during the variable creation time?

No, because it isn't an error to use '1abc' as a dictionary key.

"locals()['1abc'] = 55" does not create a variable. It creates an object 
55, a string '1abc', and uses that string as the key in a dict with 55 as 
the value.

"locals()['abc'] = 55" does not create a variable either. It does exactly 
the same thing as above, except that in this case 'abc' happens to be a 
valid identifier.

"abc = 55" also does not create a variable. What it does is exactly the 
same as the above, except that the dictionary key is forced to be a valid 
identifier by the parser (or perhaps the lexer): the parser won't accept 
1abc as a valid identifier, so you can't execute "1abc = 55".

(Almost... there's actually a slight complication, namely that making 
changes to locals() inside a function does not work.)

Python's programming model is based on namespaces, and namespaces are 
implemented as dictionaries: so-called "variables" are key/value pairs 
inside a dictionary. Just because a dictionary is used as a namespace 
doesn't stop it from being used as a dictionary: you can add any keys/
values which would otherwise be valid. It's still a dictionary, just like 
any other dictionary.

>>> globals()[45] = None
>>> globals()
{'__builtins__': <module '__builtin__' (built-in)>, 45: None, '__name__': 
'__main__', '__doc__': None}


As for *why* this is done this way, the answer is simplicity of 
implementation. Dictionaries don't need to care about what counts as a 
valid identifier. Only the lexer/parser needs to care.


-- 
Steven



More information about the Python-list mailing list