Calling a function from a set variable? [duplicate] - python

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)()

Related

Calling a function in Pycharm

I am new in Python and I am currently learning OOP in Pycharm.
When I type in a simple function like type(mylist), I dont see the answer in the console, I have to add print in the beginning, same with any other function, although in the tutorials I am currently following, they just call the function by typing its name and adding a parameter.
Same with my first attribute (please see screenshots)
Please help me if you know how to get around it.
You need to separate the object instantiation from the print()
my_dog = Dog(mybreed='lab')
print(my_dog)
Instead of:
print(my_dog=Dog(mybreed='lab'))
You could either split it to two lines:
my_dog = Dog(mybreed='lab')
print(my_dog)
Or, if you don't need the my_dog variable:
print(Dog(mybreed='lab'))
In python variable_name = expression can't be regarded as expression to be used as parameter, so print(my_dog=Dog(mybreed='lab')) will raise an error.
You can sure finish your job by this way:
my_dog = Dog(mybreed='lab') # assign the variable my_dog
print(my_dog) # print the variable my_dog
If you don't need variable my_dog, you can just use print(Dog(mybreed='lab')), which will surely work.
If you do prefer assign a variable and pass it as a parameter (just like C++ does), you can use Assignment Expressions(also The Walrus Operator) := in Python 3.8 or higher version:
print(my_dog:=Dog(mybreed='lab'))
But just keep it in mind that this operator maybe not as convenient as you think!

Executing a function in a dictionary | Python 3

So I am making a program in python 3.6 that selects and executes a specific function based on the user_input.
The code can properly decide what function to execute, just not actually execute it. The functions also work
def addition():
1+1
user_input = input("What operator do you wish to use?")
myOperators = {"Addition":addition}
if user_input in myOperators:
myOperators.get(user_input)
Using this code the function addition() never executes. However, I can check that it selects the correct value, because if I do this:
if user_input in myOperators:
print(myOperators.get(user_input))
it prints <function addition at 0x7f0973026620>
Python treats functions as object which can be passed around and stored in lists and dictionaries. To actually call the function you need to use parenthesis after the object.
In your case myOperators.get(user_input) returns the function object, so it would become
myOperators.get(user_input)()

what is the meaning of eval() in x=eval(input("hello"))? [duplicate]

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).

Using raw_input() without assigning a variable

I've only recently begun learning python2, and this is the way I see raw_input().
If suppose I write name = raw_input("What's your name? ") then I ask the user to enter something which gets stored as a string assigned to the variable name. By assigning it to name, I can use it for whatever purpose I needed it later.
But what does using raw_input() without assigning the input to a variable accomplish? Also pressing enter at this point is supposed to continue with the script (so I have deduced, am I right?), but where is this behaviour documented? In what kind of a situation would I use raw_input() without assigning to a variable? I couldn't find my answers in the official python documentation. http://docs.python.org/2/library/functions.html#raw_input
THanks
For debugging purposes you may just want your code to pause for a second so you can analyse some print statements describing what's happening in your code. There's really not set reason for having this, it's up to you.
raw_input() can be used with int() to set the length of a loop based on what the user chooses without declaring a variable.

Why can't I "string".print()?

My understanding of the print() in both Python and Ruby (and other languages) is that it is a method on a string (or other types). Because it is so commonly used the syntax:
print "hi"
works.
So why doesn't "hi".print() in Python or "hi".print in Ruby work?
When you do something like "hi".print(), you are implying that the string object "hi" has a method print. This is not the case. Instead, print is a function that takes a string (or other types) as input.
Ruby does have a method Object#display (doc here), which sends a representation of the object to the current output stream, or one specified as an argument.
(I find that it's hard to work with in irb if I use ; at the end of a line to suppress the printing of the return value; if I do that, display's output isn't shown, even if I flush the stream.)
It's not a method on a string. Prior to Python 3, it was a statement (just like break or import), and you could use both print "hi" and print("hi"). From Python 3, it was replaced by a function, thus you can no longer use print "hi":
Print Is A Function
The print statement has been replaced with a
print() function, with keyword arguments to replace most of the
special syntax of the old print statement (PEP 3105).
Why should it work? String classes rarely have void print methods - and you would never need them, because the standard static print function can print those strings anyway. It is important to note: method(someObject) is not necessarily the same as someObject.method().
What do you propose str.print should do?
print to stdout? how about stderr? or a file? or a serial port?
Printing to stdout is really a special case but it's so ubiquitous that sometimes it can be overlooked.
Then we'd have to specify where str should print to every time we create a string?
At the very least we'd have to say
"foo".print(sys.stdout)
Hopefully that looks awful to you too. It's a confusion of responsibilities
print isn't a method on a string in Python (or in Ruby, I believe). It's a statement (in Python 3 it's a global function). Why? For one, not everything you can print is a string. How about print 2?
In case you are more happy to use a method rather than a statement in Ruby you can use the method display ("test".display) to achieve this or define a new method easily like
class String
def print
puts self
end
end
and use it like this
"test".print

Categories