Executing a function in a dictionary | Python 3 - python

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

Related

Running function code only when NOT assigning output to variable?

I am looking for a way in python to stop certain parts of the code inside a function but only when the output of the function is assigned to a variable. If the the function is run without any assignment then it should run all the inside of it.
Something like this:
def function():
print('a')
return ('a')
function()
A=function()
The first time that I call function() it should display a on the screen, while the second time nothing should print and only store value returned into A.
I have not tried anything since I am kind of new to Python, but I was imagining it would be something like the if __name__=='__main__': way of checking if a script is being used as a module or run directly.
I don't think such a behavior could be achieved in python, because within the scope of the function call, there is no indication what your will do with the returned value.
You will have to give an argument to the function that tells it to skip/stop with a default value to ease the call.
def call_and_skip(skip_instructions=False):
if not skip_instructions:
call_stuff_or_not()
call_everytime()
call_and_skip()
# will not skip inside instruction
a_variable = call_and_skip(skip_instructions=True)
# will skip inside instructions
As already mentionned in comments, what you're asking for is not technically possible - a function has (and cannot have) any knowledge of what the calling code will do with the return value.
For a simple case like your example snippet, the obvious solution is to just remove the print call from within the function and leave it out to the caller, ie:
def fun():
return 'a'
print(fun())
Now I assume your real code is a bit more complex than this so such a simple solution would not work. If that's the case, the solution is to split the original function into many distinct one and let the caller choose which part it wants to call. If you have a complex state (local variables) that need to be shared between the different parts, you can wrap the whole thing into a class, turning the sub functions into methods and storing those variables as instance attributes.

How do I call a function based on user input in Python 3?

I am currently trying to create a program that learns through user input, however it converts to a string automatically.
Here's the code. I use the shelve module to store the commands for the code.
ok = {str(name):func}
asd.update(ok)
print(asd)
data["cmd"] = asd
data.close()
The 'asd' list contains every command which has been extracted from the shelf. I want to update it and store it, so next time it updates when calling a command.
'func' is the variable that stores the name of the function am trying to call, but string objects cannot be called.
How do I solve this?
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
EDIT:
This has been solved (I totally forgot about eval() )
Not sure what you're trying to achieve here, but from what I've understood you should have a look to eval()
The eval() function evaluates the specified expression, if the expression is a legal Python statement, it will be executed.
More information here

Python issue when returning function from another file

I'm having a bit of an issue when trying to return a function from another file.
main.py:
from master_input import load_input
class Vera(object):
def __init__(self):
masterinput = load_input()
self.masterinput = masterinput
def load_masterinput(self):
return self.masterinput
master_input.py:
import sys
def load_input():
if sys.version_info <= (3,0,0):
masterinput = raw_input()
elif sys.version_info >= (2,7,11):
masterinput = input()
return masterinput
There seems to be no output when running the first file. I want it to return masterinput in the second file because if I were to end the function with load_input(), in the second file, it would just output without even returning self.masterinput in the first file.
You don't show an example of instantiated one of the Vera() options nor to you show any methods that would be using (displaying/printing or otherwise manipulating) this masterinput attribute of your Veta() instance.
So it seems quite likely that your code doesn't seem to be "doing" anything. You'd declared what the objects look like, how to instantiate them and how to respond to a (poorly named) load_masterinput() method call.
Also your module isn't returning a function. When an object is instantiated it, that could will be returning a string, the result of calling either the input() or raw_input() built-in function.
By the way, the smart way, in my opinion, to handle the change from Python2.x raw_input() to Python3 input() is to use code like this:
#!python
if 'raw_input' in dir(__builtins__):
input = raw_input
Note that I'm assigning the function raw_input to the name input ... I'm NOT calling the function and assigning the results of its evaluation here.
Then all my code can use input() and we can forget that the Python2 (evaluated) input() semantics ever existed.
If I want to actually return a function from a function here's one way to do so:
#!python
# filename: my_input.py
def get_input_function():
if 'raw_input' in dir(__builtins__):
# Python2.x and earlier
return raw_input
else:
# Python3
return input
... I would then call this something like so:
#!python
import my_input
input = my_input.get_input_function()
This is unnecessarily obtuse. There's no reason to do something like this for something so trivial. There are cases where you might imagine calling some function, with certain arguments and returning different functions based on those arguments. However, in most cases, you'd still be better off creating a class and instantiating an instance of that.
The problem is that you aren't actually returning the functions, but are instead calling the functions and returning the result. Just remove the parentheses to change the function calls into the functions themselves. I.e., change:
return func()
to:
return func
The return value will then be a callable function.

Calling a function from a set variable? [duplicate]

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

Python - function setting external variable to user input as side effect

I'm a casual gamer and hobbyist programmer who knows a bit of Python. I'm trying to make a simple text adventure game engine, so I need to get raw input from the player.
This is Python 3.2.2, so my line is this:
var = input("What do you want to do? ").lower()
And that line works, but rather than typing that whole line I'd like to make it into a function (something like "getinput()"). From what I've read about input() and functions I'm looking for a function that doesn't return anything, but changes another variable's state (here "var") as a "side effect."
I do have a working function "halt()" that takes no arguments:
def halt():
input("(Press Enter to continue...) ")
print("")
Calling "halt()" gives the prompt, waits for Enter, then prints a blank line and moves on, which I intended.
The function I'm trying to get to work looks like this:
def getinput(x):
x = input("What do you want to do? ").lower()
print("")
After defining getinput(x):
var = ""
getinput(var)
print(var)
That snippet does not print the user's input, and I'm confused as to why. What do I need to do to make this work in the intended fashion?
Is what I'm trying to do impossible with a function, or is there just something I don't know about scope? Should I be at codereview?
You are right that the issue is about scope. The x in this line:
x = input("What do you want to do? ").lower()
Does not change the value that is passed to it- it creates a new variable (also called x) in the local scope of the function.
The right way to do this would be:
def getinput():
return input("What do you want to do? ").lower()
x = getinput()
print(x)
NOTE: If you are going to use any version of Python before 3.x, definitely consider using the raw_input() function as the plain input() function only takes input that is SYNTACTICALLY VALID from the user, otherwise a SyntaxError will be raised.
I'm not sure what you're trying to do exactly, but I've moved around what you've written above so that it will work. Here's what I suggest trying:
First the function getinput()...
def getinput():
x = raw_input("What do you want to do? ").lower() #prompts for the value of x
print "" #prints a blank line
return x
Then the second part...
var = getinput()
print(var)
When you pass something to a Python function, it's generally impossible to modify it unless it's mutable. That restricts you to a small subset of Python types such as a list or dictionary.
def getinput(x):
x[0] = input("What do you want to do? ").lower()
print("")
var = [""]
getinput(var)
print(var[0])
You're far better off letting the function return a value. That's the way Python was meant to work.
var is a python string variable which is being passed by value to your getinput function, which means that your getinput function only modifies a local copy of the name "x", not the value pointed to by "x" from your calling scope.
Also in Python strings are immutable and so it is impossible to modify a string's underlying value in-place due to string interning/hash consing - you merely create a new string. You should really be returning your value:
x = getinput()
But if you still want to stick to your existing design, you can pass this string variable by reference by wrapping it in a list or other reference type:
def getinput(li):
li.append(input("What do you want to do? ").lower())
print("")
usage:
x = []
getinput(x)
print x[0]

Categories