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?
Python locals() Function The locals() function returns the local symbol table as a dictionary. A symbol table contains necessary information about the current program.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With