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.
Related
This question already has answers here:
List user defined variables, python
(5 answers)
Closed 6 years ago.
This have been searched on Google and on Stack-Overflow, before asking the question, without success. Hence, this is not a trivial question...
I have two modules : Main and module1 and am doing this code in Main :
import module1
dict1= module1.getdict_userdefinedvariable()
dict1 is then manipulated in a programmatic way to check (assertion, validation,..).
However, if in getdict_userdefinedVariable(), I am using Globals() or Vars(),
I have access ONLY to the variables defined in the sub-module.
Also, Globals(), Vars() or Ipython who_ls gives the list of all names including user-defined module names, user-defined function names.
So,How can we get variables defined in Main module and filter only user-defined variables by removing USER defined module, USER defined function names ?
There is
who_ls in ipython,
but it contains module and function names....
Does not this really work for You? I tried - got my vars listed:
All credits to Niek de Klein, this is his answer from:
List user defined variables, python
If you don't put any underscores in front of your variables you could do:
#!/us/bin/python
foo1 = "Hello world"
foo2 = "bar"
foo3 = {"1":"a", "2":"b"}
foo4 = "1+1"
for name in dir():
if not name.startswith('__'):
myvalue = eval(name)
print name, "is", type(myvalue), "and is equal to ", myvalue
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?
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
declaring a global dynamic variable in python
>>> def f():
global cat
exec 'cat'+'="meow"'
return
>>> f()
>>> cat
Traceback (most recent call last):
File "<pyshell#23>", line 1, in <module>
cat
NameError: name 'cat' is not defined
This is just a stripped down example of the issue I've come across. In my actual script, I need various instances of a class be created and named, hence the exec statement.
Just calling
exec 'cat'+'="meow"'
directly in the shell works fine, but as soon as it's packed in a function, it doesn't seem to work anymore.
I still don't understand why you are using exec, its a bad design choice and alternatives are usually easier, for example instead of global and then something else you could simply do this
ns = {}
def f():
ns["cat"] = "miow"
print ns
Now isn't that cleaner?
looks like the exec ignores the global, the documentation is a bit vague. but this works:
>>> def f():
... global cat
... exec 'global cat; cat'+'="meow"'
...
>>>
>>> f()
>>> cat
'meow'
#This code does the checking of the function input.
import re
import sys
def pyexam(file_name):
fp = open(file_name)
testCaseInput = open('input.txt','r')
testCaseOutput = open('output.txt','r')
eval(compile(fp.read(),'prob.txt','exec'))
if add(int(testCaseInput.read())) == int(testCaseOutput.read()):
print "yes"
else:
print "no"
file_name ='prob.txt'
pyexam(file_name)
The file prob.txt has an add module.
This works without enclosing it in a function. Also, it works when I send the file name as the parameter. So, its very confusing as to why it is not working when I send the filename as a parameter to the function module. The error I get is this:
File "exam.py", line 13, in pyexam
if add(int(testCaseInput.read())) == int(testCaseOutput.read()):
NameError: global name 'add' is not defined
Use exec instead of eval.
The eval() function is for evaluating expressions and returning (not assigning) a result:
>>> x = eval('3+5')
>>> x
>>> 8
The exec statement executes statements including assignments:
>>> exec 'y = 3 + 5'
>>> y
>>> 8
See http://docs.python.org/reference/simple_stmts.html#the-exec-statement and http://docs.python.org/library/functions.html#eval .
Also note that your code and my examples work with the globals() or module-level namespace. Due to CPython fast local optimizations, local variables aren't available for writing by exec.
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.