Question about locals()

Terry Reedy tjreedy at udel.edu
Tue May 19 01:54:03 EDT 2009


Gökhan SEVER wrote:
> Hello,
> 
> Could you please explain why locals() allow me to create variables that 
> are not legal in Python syntax.

It doesn't.

> Example: locals()['1abc'] = 55. Calling 
> of 1abc results with a syntax error.

Within a function, locals() is a persistemt dictionary copy of the local 
namespace.  In that situation, using even a legal name as the key does 
not change the local namespace, and trying to use that legal name will 
give a NameError.

Better to ask about globals(), which *is* the global namespace.

  Shouldn't it be better to raise an
> error during the variable creation time?

To do that would require a separate legal-name-string-only dictionary.
That has been considered, but has not seemed worth the trouble.
Also, people have found uses for what you are calling an error.

Few newbies try to add non-identifiers to locals().  More often, they 
fail to real the red warning about not trying to add even a legal 
identifier.

Terry Jan Reedy




More information about the Python-list mailing list