1
I have a function that gets an account and calculates it using the function eval
. My question is, how can I be more cautious in using this function ?
def calcula(string):
if type(eval(string)) in [float, int]:
resultado = eval(string)
return resultado
conta = str(input('Digite a conta'))
# Ex: '5**2 + 0.5'
calcula(conta)
I created a validation for the string in if
. This is enough to prevent user input from affecting the program ?
It’s not easy to give an answer to that. I think it would be quite long. In essence you will only be safe sanitizing the typed content, which is a very complicated process. Maybe you have a library that already does this. If you don’t do this you’re not being cautious and all kinds of security issues can occur. Of course, in an exercise this is not relevant, but you will be exercising the wrong way to do it and you will learn that the
eval()
is nice. https://answall.com/q/128845/101. The ideal is to learn to do it right or not to do it wrong.– Maniero
Usually the problem of Eval is who uses it. If the function exists, there is a reason, but unfortunately it is not used right virtually never. The people who defend a lot Without criteria usually have lazy programming, prefer to "huddle" code. This case of yours is clearly not the case of Val, because doing a "fix" to make Val safe is more critical than doing the right code without Val (and in this case, doing it right is smarter in every way). See comment on the current answer accepted.
– Bacco
Related: https://answall.com/a/450398/112052
– hkotsubo
@hkotsubo I knew I had yours, do not remember it was so recent and the same person. It is the same case to have the overwhelming majority of questions with query suffering from SQL Injection. People want to do wrong anyway.
– Maniero