Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is it bad idea to modify locals in python?

Tags:

python

locals

Related to this reply here. Locals' doc here.

The docs mention that the dictionary should not change, not sure what it means but would locals() be applicable in lab-reports where data won't change, for example in measurements?

like image 446
hhh Avatar asked Feb 14 '11 20:02

hhh


People also ask

What does locals () do in Python?

Python locals() Function The locals() function returns the local symbol table as a dictionary. A symbol table contains necessary information about the current program.

What is locals and globals in Python?

By Malhar Lathkar. 06 Jan 2021. The built-in functions globals() and locals() returns the global and local symbols table respectively. Python interpreter maintains a data structure containing information about each identifier appearing in the program's source code.


1 Answers

Modification is a bad idea because the documentation (which you link) explicitly says not to:

Note: The contents of this dictionary should not be modified; changes may not affect the values of local and free variables used by the interpreter.

You don't need any more reason than that.

If you are using it in a way that doesn't modify any variables, then you'll be fine, but I'd question the design and see if there's a better way to do what you want.


In the specific example you link, locals is actually globals(), as you use it in the global scope of a module. This very specific use works now and, though I expect it to continue to work just as with globals, you might as well just use globals instead.

An even cleaner solution is probably, without knowing the rest of your design, to use a regular ol' dictionary for your variables; then use data["x"] = value instead of globals()["x"] = value.

like image 55
Fred Nurk Avatar answered Oct 07 '22 01:10

Fred Nurk