In the previous lesson, I showed you more information about expressions that
eval() can use. In this lesson, I’m going to show you how to compile an expression.
Up until now, I’ve only been demonstrating how to pass a string into
eval(). You can also pass in a pre-compiled object. Pre-compiled objects are returned by the built-in
The three mandatory parameters to compile that you need are
source is the code to compile.
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.
mode indicates how to compile. If you want to compile something that would be a valid expression that
eval() could take as a string, pass in
"eval" as the
01:00 So, here I go. Let me compile an expression.
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
Similarly to using
eval() directly, if I pass in something that isn’t an expression or a invalid expression, I will get a
In addition to having the
compile() also supports the
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.
I can pass in a
code object and it will work.
If I pass in something that was compiled in
eval() will return a response just like if you put a string into
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.
And as further proof that everything in Python is an object, even this
code is an object. One of the members of this object tells you what functions are compiled inside of it.
By looking at
.co_names, you can see the
math library is referenced.
'pi are all used.
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.