This question already has answers here:
What does Python's eval() do?
(12 answers)
Closed 9 years ago.
what does x=eval(input("hello")) mean, doesn't it suppose to be instead of eval() something like int? I thought of x as a variable that belong to some class that determine its type, does eval include all known classes like int float complex...?
eval, like the documentation says, evaluates the parameter as if it were python code. It can be anything that is a valid python expression. It can be a function, a class, a value, a loop, something malicious...
Rule of thumb: Unless there is no other choice, don't use it. If there is no other choice, don't use it anyway.
eval() will interpret the content typed by the user during the input(). So if the user type x+1 with x equals to 1 in locals, it will output 2 (see below).
An extract from the documentation:
The expression argument is parsed and evaluated as a Python expression (technically speaking, a condition list) using the globals and locals dictionaries as global and local namespace.
>>> x = 1
>>> print eval('x+1')
2
It can be dangerous, since the user can type whatever he wants, like... some Unix command. Don't use it, unless you know what you are doing (even so, it leads to serious security flaws).
Related
This question already has answers here:
What does the Ellipsis object do?
(14 answers)
Closed 2 years ago.
What's the difference between the pass statement:
def function():
pass
and 3 dots:
def function():
...
Which way is better and faster to execute(CPython)?
pass has been in the language for a very long time and is just a no-op. It is designed to explicitly do nothing.
... is a token having the singleton value Ellipsis, similar to how None is a singleton value. Putting ... as your method body has the same effect as for example:
def foo():
1
The ... can be interpreted as a sentinel value where it makes sense from an API-design standpoint, e.g. if you overwrite __getitem__ to do something special if Ellipsis are passed, and then giving foo[...] special meaning. It is not specifically meant as a replacement for no-op stubs, though I have seen it being used that way and it doesn't hurt either
Not exactly an answer to your question, but perhaps a useful clarification. The pass statement should be use to indicate a block is doing nothing (a no-op). The ... (ellipsis) operator is actually a literal that can be used in different contexts.
An example of ellipsis usage would be with NumPy array indexing: a[..., 0]
This question already has answers here:
Obtaining closures at runtime [duplicate]
(1 answer)
How to open a closure in python?
(5 answers)
Closed 2 years ago.
I would like to know if there is any method to check whether two functions have the same arguments at runtime in python 3.
Basically, I have this function (func) that takes two arguments and perform some sort of computation. I want to check whether or not a and b have the same arguments' values at runtime
a = func(2, 3)
b = func(2, 3)
a.argsvalue == b.argsvalue
It is not feasible to run the code before and check the results because I am implementing a lazy framework. My main goal is to be able to understand what are the arguments of the function because there is one variable argument that I do not care but there is one static that is created before running the function.
##EDIT
I actually solved this problem using the inspect module (getclosure) for those who are interested. Thank you so much for the comments it helped me to familiarize myself with the terminology. I was actually looking for the closure, which I assigned dynamically.
when you do this - a.argsvalue == b.argsvalue you try to access a member of the value returned from the function.
so, if your "func" would return an object having the args you called it with (which sound like a weird thing to do) you would be able to access it.
anyway, if you need these values, just store them before sending them to the function, and then you can do whatever you want with them.
This question already has answers here:
How can I select a variable by (string) name?
(5 answers)
How do I create variable variables?
(17 answers)
Closed 2 years ago.
In unix shell script:
if I call
function_name "${!variable}" -> variable will replaced during the execution/runtime
is there something alternative exists in python? there are some other logic involved prior creating the variable. But I'm interested in {!variable} alternative.
You are looking for the eval function:
a = "there"
b = "a"
eval(b)
Yielding the output:
'there'
Of course, the eval function, while being a bit more verbose than the bash indirect variable reference, is also much more versatile, as you can have the indirectly referenced variable (b in this case), contain any python expression.
In python functions are 1st class objects. Which means you can pass them around just like any variable.
def print_this():
print('this')
def print_that():
print('that')
p1 = print_this
p2 = print_that
p1()
p2()
So you don't need to use eval.
This question already has answers here:
Running exec inside function
(3 answers)
Creating dynamically named variables in a function in python 3 / Understanding exec / eval / locals in python 3
(2 answers)
Closed 4 years ago.
EDIT: This question is NOT ANSWERED BY THE LINKS ABOVE that a mod added. As I said before in a comment, Python 3 brought changes, and the examples given in those answers were for Python 2. If I compile those in my Python 3 environment, I get the same error as here.
Consider
str = "x = [113, 223]"
exec(str)
print(x[0]) #113
This works perfectly. But if I want this code to be executed in a function, it returns an error NameError: name 'x' is not defined. Here's a minimal working example:
def some_code():
str = "x = [1, 2]"
exec(str)
print(x)
some_code()
What is going on here?
I need a solution to
use exec inside the function (because ultimately its a tkinter function -see the first edit history of this question- and I'm reading this from a file that should be executed
I would like to easily be able to refer to x, because I will need to do that in a lot of places. So using a long line of code to refer to x will be cumbersome.
Naively moving the relevant code to first level scope solved it.
string = "x = [113, 223]"
exec(string)
def some_code():
print(x[0]) #113
Another approach: I started toying around with exec() more and from what I can see exec() writes its results (in this case x) into the locals() and globals() builtin dictionaries. Therefore, the following is another solution to the problem, but it seems rather hacky:
def some_code():
string = "x = [113, 223]"
exec(string)
print(locals()['x'][0]) #113
some_code()
In the same manner, you can define your own dictionary for use instead of locals() where exec() stores x, which in my opinion is much cleaner:
exec_results = {}
def some_code():
string = "x = [113, 223]"
exec(string, None, exec_results)
print(exec_results['x'][0]) #113
some_code()
I highly discourage using exec() for really simple cases such as this, but if you wish to use it in the future, I highly suggest checking out other threads on the same topic that were created prior to this question, such as running-exec-inside-function and globals and locals in python exec(). Check out the Python docs on exec() to read more about exec() as well.
This question already has answers here:
Calling a function from string inside the same module in Python?
(2 answers)
Python function pointer
(8 answers)
Closed 9 years ago.
Im writing a python script and what I would like to do is capture the input into a variable and then use that to call a function with that name. Here is an example:
def test():
print "You want to do a test!"
option = raw_input("What do you want to do? ") #User types in test
option()
Now this isnt working since python is not seeing option as a variable but rather is trying to call the function "option". What is the bast way to go about doing this?
eval() will work, but as #MattDMo said it can be dangerous.
A much safer way to do this, if your functions are module globals:
globals()[option]()
globals() is a dictionary mapping strings to the module global objects those strings are bound to. So globals()[option] looks up the string bound to option in that dict, and returns the object; e.g., globals["test"] returns the function object for test(). Then adding () at the end calls that function object. Bingo - you're done.
You want to be very careful about running arbitrary code, but if you absolutely need to, you can use the eval() function.
What might be a better way is to give your user a menu of options, then do testing on the contents of option to see which one they picked, then run that function.
You can use python eval.
From the help page, eval evaluates the source in the context of globals and locals. The source may be a string representing a Python expression or a code object as returned by compile().
For example:
def a():
print "Hello"
inp = raw_input()
eval(inp + "()")
On entering a at the stdin, the function a will be executed. Note that this could be dangerous without any safety checks.
This is, I suppose, an actual use for bare input:
option = input("What do you want to do? ") #User types in test
option()
This is semantically equivalent to eval(raw_input()). Note that in python 3, raw_input becomes input so you will explicitly have to eval it.
The usual caveats of this type of operation being incredibly unsafe apply. But I think that's obvious from your requirement of giving the user access to run arbitrary code, so...
I like using a dict in situations like this. You can even specify a default option if the user provides an answer that isn't expected.
def buy_it():
print "use it"
def break_it():
print "fix it"
def default():
print "technologic " * 4
menu = {"buy it": buy_it, "break it": break_it}
option = raw_input("What do you want to do? ")
menu.get(option, default)()