Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Python Using Databases in Python Our Diary App Switching It Up

David Ton-Lai
David Ton-Lai
3,268 Points

Not sure about "menu[choice]()"

I understood Kenneth's explanation for most of the code, but I'm not sure why there are parens after menu[choice](). I know it's a dictionary, so menu[choice] is refers to the key in the dictionary. Is the () a special attribute of OrderedDicts?

2 Answers

Chris Freeman
MOD
Chris Freeman
Treehouse Moderator 68,423 Points

There is a bit of trickery here that shows off the power of "functions as first class citizens". If the dictionary menu is populated with values that are functions, then menu[choice] will return one of these functions.

Since functions can be passed around just like variables, the function can be returned by menu[choice] as a 'non-executed object which can subsequently be executed by simply added the parens () to signify executing the function.

A longer way to write this would be:

some_func = menu[choice]
some_func()

# or combining into one statement:
menu[choice]()
David Ton-Lai
David Ton-Lai
3,268 Points

Wow that's cool, I hadn't considered that. Thanks for clearing that up Chris!

Jonathan Prada
Jonathan Prada
7,039 Points

Exactly what i wanted to know, that is cool