This would be the same as the
expression that’s passed into
eval() in string mode. The
filename is used to indicate where the source code comes from. In the case of
eval(), you really don’t care, so you can pass in
"<string>" to tell it that it’s a string.
This creates an object that is inside the
code variable. The expression being compiled is
"2 + 3", and it has the indicator that this is a string and that it’s being compiled in
"eval" mode. Now I can pass that
code object into
eval(), and I get the result, no different than if I had passed the string into
The difference here is that it compiles in the same pattern as the
exec() function. This means it’s not just expressions, but statements as well that can be compiled. Interestingly enough,
eval() doesn’t actually care what the code was compiled with.
If I pass in a
code object that was compiled with
exec() doesn’t return a result, so
eval() will return
None. Now that I have
math imported, I can compile something a little more complicated.
This gives you the ability to introspect what has been passed in and compiled. Next up, I’ll delve into the security risks of using
eval(), how some people attempt to avoid it, and why that’s still a problem.
Become a Member to join the conversation.