Question about locals()

Gökhan SEVER gokhansever at gmail.com
Tue May 19 19:06:04 CEST 2009


Thank you all for great explanation on this subject. Maybe a few sentences
from these conversations could be added to locals() documentation.

I will make double sure myself while using locals() to end up with valid
identifiers.

Gökhan


On Tue, May 19, 2009 at 1:06 AM, Steven D'Aprano <
steven at remove.this.cybersource.com.au> wrote:

> 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
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20090519/778cd903/attachment.html>


More information about the Python-list mailing list