What does Python's eval() do?
The eval function lets a Python program run Python code within itself.
eval example (interactive shell):
>>> x = 1
>>> eval('x + 1')
2
>>> eval('x')
1
What does model.eval() do in pytorch?
model.eval()
is a kind of switch for some specific layers/parts of the model that behave differently during training and inference (evaluating) time. For example, Dropouts Layers, BatchNorm Layers etc. You need to turn off them during model evaluation, and .eval()
will do it for you. In addition, the common practice for evaluating/validation is using torch.no_grad()
in pair with model.eval()
to turn off gradients computation:
# evaluate model:
model.eval()
with torch.no_grad():
...
out_data = model(data)
...
BUT, don't forget to turn back to training
mode after eval step:
# training step
...
model.train()
...
Difference between eval(input()) and eval(input()) in Python
eval
evaluates a piece of code. input
gets a string from user input. Therefore:
eval(input())
evaluates whatever the user enters. If the user enters123
, the result will be a number, if they enter"foo"
it will be a string, if they enter?wrfs
, it will raise an error.eval("input()")
evaluates the string"input()"
, which causes Python to execute theinput
function. This asks the user for a string (and nothing else), which is while123
will be the string"123"
,?wrfs
will be the string"?wrfs"
, and"foo"
will be the string'"foo"'
(!).
A third version that might make the difference apparent: eval(eval("input()"))
is exactly identical to eval(input())
.
Use of eval in Python?
eval
and exec
are handy quick-and-dirty way to get some source code dynamically, maybe munge it a bit, and then execute it -- but they're hardly ever the best way, especially in production code as opposed to "quick-and-dirty" prototypes &c.
For example, if I had to deal with such dynamic Python sources, I'd reach for the ast module -- ast.literal_eval
is MUCH safer than eval
(you can call it directly on a string form of the expression, if it's a one-off and relies on simple constants only, or do node = ast.parse(source)
first, then keep the node
around, perhaps munge it with suitable visitors e.g. for variable lookup, then literal_eval
the node) -- or, once having put the node in proper shape and vetted it for security issues, I could compile
it (yielding a code object) and build a new function object out of that. Far less simple (except that ast.literal_eval
is just as simple as eval
for the simplest cases!) but safer and preferable in production-quality code.
For many tasks I've seen people (ab-)use exec
and eval
for, Python's powerful built-ins, such as getattr
and setattr
, indexing into globals()
, &c, provide preferable and in fact often simpler solutions. For specific uses such as parsing JSON, library modules such as json
are better (e.g. see SilentGhost's comment on tinnitus' answer to this very question). Etc, etc...
What does the eval() function do in Python?
In your code, the answer
variable is what the user enters in response to your request for input
. It's their answer to your question. The result
variable is the correct answer to your randomly generated question. What you want to do is check whether their answer
is the same as the expected result
(which is why I called that variable correct_answer
in my answer to your previous question).
The reason for using eval
is that it evaluates an expression which is passed as a string. So for example if you pass "2*3" to eval
it will return 6.
The documentation for eval
is here which is always a good place to start.
Breaking down the line which is giving you trouble:
result = eval(str(number1)+oper+str(number2))
Breaks down for an example where number1
is 4 and number2
is 7:
result = eval("4*7")
The "4*7" is then converted by eval
from the string "4*7" to the source code 4*7
which is then calculated out to be 28
.
I think the difficulty you're having is seeing that there is a difference between "4*7" which is a string, and 4*7
which is a code statement. What eval
does is convert strings to statements which can then be executed as code.
what is the difference between eval and int
eval
evaluates the python expression. In python 3, numbers starting by 0
aren't allowed (except for 0000
, see Why does 000 evaluate to 0 in Python 3?). In python 2, those are interpreted as octal (base 8) numbers. Not better... (python 3 base 8 now uses exclusively Oo
prefix)
int
performs a string to integer conversion, so it cannot evaluate a complex expression (that you don't need), but isn't subjected to this leading zero syntax.
Another nice feature is that you can check if the entered expression is an integer by using a simple and qualified try/except
block:
while True:
try:
age = int(input("enter age"))
break
except ValueError:
print("Retry!")
(with eval
you would have to protect against all exceptions)
Advice: use int
, because it's safer, doesn't have security issues (eval can evaluate any expression, including system calls and file deletion), and suits your purpose perfectly.
Note: the above code is still unsafe with python 2: input
acts like eval
. You could protect your code against this with the simple code at the start of your module:
try:
input = raw_input
except NameError:
pass
so python 2 input
is not unreachable anymore and calls raw_input
instead. Python 3 ignores that code.
Using python's eval() vs. ast.literal_eval()
datamap = eval(input('Provide some data here: '))
means that you actually evaluate the code before you deem it to be unsafe or not. It evaluates the code as soon as the function is called. See also the dangers of eval
.
ast.literal_eval
raises an exception if the input isn't a valid Python datatype, so the code won't be executed if it's not.
Use ast.literal_eval
whenever you need eval
. You shouldn't usually evaluate literal Python statements.
Related Topics
Display Number With Leading Zeros
List Comprehension on a Nested List
How to Use Raw_Input in Python 3
Multiple Aggregations of the Same Column Using Pandas Groupby.Agg()
Deleting Dataframe Row in Pandas Based on Column Value
How to Install Pip With Python 3
How to Count the Frequency of the Elements in an Unordered List
Process Escape Sequences in a String in Python
Spawning Multiple Instances of the Same Object Concurrently in Python
How to "Log In" to a Website Using Python'S Requests Module
How to Hide Output of Subprocess
Why Does Substring Slicing With Index Out of Range Work
How to Find the Location of My Python Site-Packages Directory
What Is Getattr() Exactly and How to Use It
Permutations With Unique Values