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 55,555 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,036 Points

Exactly what i wanted to know, that is cool