[Tutor] args to functions in a dictionary?

Wayne Werner waynejwerner at gmail.com
Thu Aug 26 00:24:58 CEST 2010


On Wed, Aug 25, 2010 at 4:58 PM, Alex Hall <mehgcap at gmail.com> wrote:

> Hi all,
> If I wanted to have a dictionary containing functions, could I pass
> args to those functions? For example:
> menu={
>  "option 1":f1,
>  "option 2":f2
> }
> How would I pass args to f1 or f2 in this case? TIA.


You sure could, because functions are first order citizens in python,
meaning you can pass them around like any other data type.

menu['option 1']() is how you would call the functions, and you'd just put
an args/kwargs in the parenthesis.

Conceptually you can replace menu['option 1'] with f1, so anywhere you see
this:

menu['option 1'](arg1)

you can replace it with

f1(arg1)

I don't know if Python does that exact thing on the back end, but the end
result is certainly the same.

HTH,
Wayne

(p.s. Gmail's undo sending feature is terribly nice when I forget to
reply-all)
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100825/65aa340a/attachment.html>


More information about the Tutor mailing list