1

Is it possible to pass arguments to a function within a dictionary?

d = {"A": foo(), "B": bar()}

def foo(arg):
    return arg + 1

def bar(arg):
    return arg - 1

In this case I want to pass arg to bar() by referencing the function dynamically

d["B"]  #<-- pass arg to bar()
3
  • 1
    Your dictionary syntax is wrong. The parens shouldn't be there. Otherwise you're actually calling the functions immediately and storing their return values. Commented Nov 20, 2015 at 22:44
  • @Doorknob - I wouldn't really call that a problem with syntax. It's perfectly valid Python; it just won't give the right result (and functions have to be defined before they're referenced and called, of course). Commented Nov 20, 2015 at 22:47
  • @TessellatingHeckler - The foo I'm looking at in the question doesn't do that. Commented Nov 20, 2015 at 22:58

1 Answer 1

2

It's possible, but you have to refer to the function (e.g. foo) without already calling it (e.g. foo()).

def foo(arg):
    return arg + 1

def bar(arg):
    return arg - 1

d = {"A": foo, "B": bar}

Result:

>>> d['A'](5)
6
Sign up to request clarification or add additional context in comments.

2 Comments

You should add that foo references the function named foo, whereas foo() (with parens) calls it.
I thought that was pretty clear since it was the only change in the code (other than eliminating the NameError), but hopefully the edit improves it.

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.