ASPN ActiveState Programmer Network
ActiveState
/ Home / Perl / PHP / Python / Tcl / XSLT /
/ Safari / My ASPN /
Cookbooks | Documentation | Mailing Lists | Modules | News Feeds | Products | User Groups


Recent Messages
List Archives
About the List
List Leaders
Subscription Options

View Subscriptions
Help

View by Topic
ActiveState
.NET Framework
Open Source
Perl
PHP
Python
Tcl
Web Services
XML & XSLT

View by Category
Database
General
SOAP
System Administration
Tools
User Interfaces
Web Programming
XML Programming


MyASPN >> Mail Archive >> python-list
python-list
Re: list/dictionary as case statement ?
by Gary Herron other posts by this author
Jan 2 2007 2:27PM messages near this date
Re: list/dictionary as case statement ? | Re: list/dictionary as case statement ?
Stef Mientki wrote:
>  If I'm not mistaken, I read somewhere that you can use 
>  function-names/references in lists and/or dictionaries, but now I can't 
>  find it anymore.
> 
>  The idea is to build a simulator for some kind of micro controller (just 
>  as a general practise, I expect it too be very slow ;-).
> 
>  opcodes ={
>     1: ('MOV', function1, ...),
>     2: ('ADD', function2, ),
>     3: ('MUL', class3.function3, )
>     }
> 
>  def function1
>     # do something complex
> 
> 
>  Is this possible ?
> 
>  thanks,
>  Stef Mientki
>    

Yes. Functions are (so called) first class objects. You can refer to one 
by name, and pass that reference around in variables and other data 
structures.

That said, your code above won't work as written because function1 is 
not in existence when you refer to it.

Here's some working code which manipulates a reference to a function 
then calls it:

 > >> def fn():
... print "Hello world!"
...
 > >> x = fn
 > >> y = [fn,fn]
 > >> z = {1:fn, 2:fn}
 > >>
 > >> x()
Hello world!
 > >> y[0]()
Hello world!
 > >> y[1]()
Hello world!
 > >> z[1]()
Hello world!
 > >> z[2]()
Hello world!
 > >>

Gary Herron


-- 
http://mail.python.org/mailman/listinfo/python-list
Thread:
Stef Mientki
Bruno Desthuilliers
Bjoern Schliessmann
Tom Plunket
Stef Mientki
Bjoern Schliessmann
Mrab
Tom Plunket
Hendrik van Rooyen
Gary Herron
Stef Mientki
Grant Edwards

Privacy Policy | Email Opt-out | Feedback | Syndication
© ActiveState Software Inc. All rights reserved