2

Here is my code:

def funcWithParam(param):
    print "Your parameter is: " + param


def justFunction():
    print "No parameters"


def wrong():
    print "wrong choice"


userInput = raw_input("type 'params' for parameters. type 'no' for no parameters: ")


if userInput == "params":
    myparam = "type your parameter: "

else:
    myparam = ""


dic = {
    "params": (funcWithParam(myparam)),
    "no": justFunction,
}

dic.get(userInput,wrong)()

I know the code is wrong and every time I run it, the "params" key is being executed with the "userInput" string. If at the param check is True and I add a 2nd argument then the program fails saying:

'NoneType' object is not callable.

I wonder what is the correct syntax / way to call a function with parameters using a dictionary.

2 Answers 2

2

That's because you construct the dictionary like:

dic = {
    "params": (funcWithParam(myparam)), #here you already call the function
    "no": justFunction, #this is a real function
}

It thus means that the dictionary does not contain a function for "params", but the result of that function. If you later fetch "params" from the dictionary, it returns None (because funcWithParam returned None) and then you try to call None (like None()) which is not supported.

You can simply convert the dictionary into a lazy one:

dic = {
    "params": (lambda : funcWithParam(myparam)),
    "no": justFunction,
}

Or even more elegantly:

dic = {
    "params": (lambda x=myparam : funcWithParam(x)),
    "no": justFunction,
}

lambda : funcWithParam(myparam) generates an anonymous function with no parameters that will call funcWithParam with myparam.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks! I didn't know about this "lambda" and it is exactly what I needed.
1

When you create the dictionary, since you're putting "params": (funcWithParam(myparam), it is being called and therefore what you are placing in the dictionary is the return value of the function.

In order to put it in the dictionary and call it by key, you need to do this:

dic = {
    "params": funcWithParam,
    "no": justFunction,
}

dic.get(userInput,wrong)(myparam)

Try running this and see what you get:

def funcWithParam(param, *args):
    print "Your parameter is: " + param

def justFunction(*args):
    print "No parameters"

def wrong(*args):
    print "wrong choice"


userInput = raw_input("type 'params' for parameters. type 'no' for no parameters: ")
if userInput == "params":
    myparam = raw_input("type your parameter: ")
else:
    myparam = ""


dic = {
    "params": funcWithParam,
    "no": justFunction,
}

dic.get(userInput, wrong)(myparam)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.