I stumbled across the following warning when I was reading Code Like a Pythonista: Idiomatic Python by David Goodger.
Excerpt from the article ...
print('Hello %(name)s, you have %(messages)i messages' % locals())
This is very powerful. With this, you can do all the string formatting you want without having to worry about matching the interpolation values to the template.
But power can be dangerous. "With great power comes great responsibility." If you use the
locals()
from with an externally-supplied template string, you expose your entire local namespace to the caller. This is just something to keep in mind.
I am trying to understand the specific scenarios in which using locals()
can be dangerous. Any examples of how the presence of locals()
in a code can be exploited are appreciated. Thanks!
Python locals() Function The locals() function returns the local symbol table as a dictionary. A symbol table contains necessary information about the current program.
The globals(), locals() and reload() Functions in PythonIf locals() is called from within a function, it will return all the names that can be accessed locally from that function. If globals() is called from within a function, it will return all the names that can be accessed globally from that function.
Global variables are declared outside any function, and they can be accessed (used) on any function in the program. Local variables are declared inside a function, and can be used only inside that function. It is possible to have local variables with the same name in different functions.
In Python or any other programming languages, the definition of local variables remains the same, which is “A variable declared inside the function is called local function”. We can access a local variable inside but not outside the function.
Sample, trivial code:
script_name = 'readpw.py'
...
entered_pw = raw_input()
if entered_pw != real_pw:
print "%(script_name)s: The password you entered: "+entered_pw+" is incorrect."%locals()
Consider the case where entered_pw is %(real_pw)s
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