This question already has answers here:
Why doesn't exec work in a function with a subfunction?
(6 answers)
Closed 8 years ago.
I'm learning the basics of eval, exec, and compile on 2.7.6.
I have hit a roadblock on exec, as I get an error when running this:
exec 'print 5'
Error:
SyntaxError: unqualified exec is not allowed in function 'main' it
contains a nested function with free variables (EvalExecCompile.py,
line 61)
I have found that exec is an expression in 2.7.6 while a function in 3.x. Problem is, I cannot find a working example to learn from for exec in 2.7.6.
I am aware of all the dangers of using exec, etc., but just want to learn how to use them encase I ever need them.
Could someone please help? Maybe provide a working example that I can dissect?
Thank you.
The goal of my question is to learn how to use exec in 2.7.6 properly.
You can't use exec in a function that has a subfunction, unless you specify a context. From the docs:
If exec is used in a function and the function contains a nested block
with free variables, the compiler will raise a SyntaxError unless the
exec explicitly specifies the local namespace for the exec. (In other
words, "exec obj" would be illegal, but "exec obj in ns (namespace)" would be
legal.)
Here is the code to implement exec:
def test2():
"""Test with a subfunction."""
exec 'print "hi from test2"' in globals(), locals()
def subfunction():
return True
test2()
This example was taken from: In Python, why doesn't exec work in a function with a subfunction?
Related
This question already has answers here:
eval SyntaxError: invalid syntax in python [duplicate]
(3 answers)
Closed 5 years ago.
Code:
eval("print('foobar')")
Output:
Traceback (most recent call last):
File "Untitled.py", line 30, in <module>
eval("print('foobar')")
File "<string>", line 1
print('foobar')
^
SyntaxError: invalid syntax
What am I doing wrong?
You have to use the exec function. Like this:
exec("print('foobar')")
See What is the difference between an expression and a statement in Python?
for more informations.
print is an operator in Python 2, and a function in Python 3. Which version do you use?
eval evaluates expressions, not statements, so you need to pass it the print function, not the print statement. By default, print is a statement in Python 2, and the print statement doesn't exist in Python 3. However, the print function is available in recent versions of Python 2 via a __future__ import. The print function is actually defined in those versions of Python 2 but it's masked by the print statement; the import makes the print statement unavailable, thus exposing the print function.
Demo, tested on Python 2.6.6:
from __future__ import print_function
eval("print('foobar')")
output
foobar
BTW, it's generally not a good idea to use eval or exec, unless you have no alternative. They are relatively slow, and have security risks if you pass them unsanitized strings to evaluate / execute. For details, please see Eval really is dangerous by SO veteran Ned Batchelder. To evaluate simple Python literals you can use ast.literal_eval.
This question already has answers here:
Python: Why should 'from <module> import *' be prohibited?
(6 answers)
Closed 5 months ago.
From the documentation:
The wild card form of import — from module import * — is only allowed at the module level. Attempting to use it in class or function definitions will raise a SyntaxError.
Why? What's the sense of avoiding to use it in a function? What's the problem?
The CPython implementation uses a special optimisation for local variables: They aren't dynamically looked up at runtime from a dictionary, as globals are, but rather are assigned indices statically at compile time, and are looked up by index at runtime, which is a lot faster. This requires the Python compiler to be able to identify all local names at compile time, which is impossible if you have a wildcard import at function level.
In Python 2, there was still a fallback mechanism that got invoked in cases where it wasn't always possible to determine all local names statically. This mechanism used a dynamic dictionary for local variables, significantly slowing down execution.
For example this code
def f():
exec "x = 2"
print x
works as expected in Python 2, whereas
def f():
exec("x = 2")
print(x)
results in a NameError in Python 3.
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
What’s the difference between eval, exec, and compile in Python?
I known that
eval is a function
exec is a statement
And the simple usage of both is :
eval('1+2')
exec 'print 1+2'
But there are other usages that I can't understand.
Using a variable to store a function name, and using this variable to
call the function
eg:
def test():
print 'hello world'
func = 'test'
func = eval(func)
func() # this will call test()
I type(func) after
func = eval(func)
it returns
<type 'function'>
I read the document of eval, but I don't known why the eval can do
this.
Using a variable to store a module name, and using this variable to import the module.
eg.
m = 'sys'
exec "import " + m
Is this the reason:
import module_name is a statement, not expression?
and:
eval does only to calculate a expression
exec does to run the statement in the str?
The part of your question about storing the function name can be explained by the fact that this would be equivalent:
def test():
print 'hello world'
func = test
func() # this will call test()
The call to eval() in your example is no different than a call like:
y = eval('x + 1')
I believe your second question is the same as this one, and the answers might be helpful.
Environment: python 2.x
If print is a built-in function, why does it not behave like other functions ? What is so special about print ?
-----------start session--------------
>>> ord 'a'
Exception : invalid syntax
>>> ord('a')
97
>>> print 'a'
a
>>> print('a')
a
>>> ord
<built-in function ord>
>>> print
-----------finish session--------------
The short answer is that in Python 2, print is not a function but a statement.
In all versions of Python, almost everything is an object. All objects have a type. We can discover an object's type by applying the type function to the object.
Using the interpreter we can see that the builtin functions sum and ord are exactly that in Python's type system:
>>> type(sum)
<type 'builtin_function_or_method'>
>>> type(ord)
<type 'builtin_function_or_method'>
But the following expression is not even valid Python:
>>> type(print)
SyntaxError: invalid syntax
This is because the name print itself is a keyword, like if or return. Keywords are not objects.
The more complete answer is that print can be either a statement or a function depending on the context.
In Python 3, print is no longer a statement but a function.
In Python 2, you can replace the print statement in a module with the equivalent of Python 3's print function by including this statement at the top of the module:
from __future__ import print_function
This special import is available only in Python 2.6 and above.
Refer to the documentation links in my answer for a more complete explanation.
print in Python versions below 3, is not a function. There's a separate print statement which is part of the language grammar. print is not an identifier. It's a keyword.
The deal is that print is built-in function only starting from python 3 branch. Looks like you are using python2.
Check out:
print "foo"; # Works in python2, not in python3
print("foo"); # Works in python3
print is more treated like a keyword than a function in python. The parser "knows" the special syntax of print (no parenthesis around the argument) and how to deal with it. I think the Python creator wanted to keep the syntax simple by doing so. As maverik already mentioned, in python3 print is being called like any other function and a syntx error is being thrown if you do it the old way.
Ok, this is funny.
>>> exec("print")
>>> help(exec)
File "<stdin>", line 1
help(exec)
^
SyntaxError: invalid syntax
>>>
looks like exec is a statement, not a function, hence you cannot help() it. Is this expected or a bug? if expected, why? can you reproduce it on python3 ? I have Python 2.6.1 here.
In Python 2.x, exec is a statement (and thus doesn't have a docstring associated with it.)
In Python 3.x, exec is now a function: http://docs.python.org/py3k/library/functions.html?highlight=exec#exec
So it can (and does) have a docstring.
You'd get this same behavior for help(print), which also became a function in 3.x.
yes, like my followers said but for me i usually do :
>>> help("exec")
>>> help("print")
and it work for python 2.* and python 3k
Just put quotes around it (works for assert, etc. too):
>>> help('exec')
http://docs.python.org/release/3.0.1/library/functions.html#exec
In Python 3, exec() is a function. Apparently, in Python 2, exec is a statement but can be used similarly to a function.
http://docs.python.org/release/3.0.1/whatsnew/3.0.html#removed-syntax
Removed keyword: exec() is no longer a keyword; it remains as a function. (Fortunately the function syntax was also accepted in 2.x.)