Dispatching functions from a dictionary

George Sakkis george.sakkis at gmail.com
Mon Mar 31 00:20:54 CEST 2008


On Mar 30, 5:06 pm, Paul Rubin <http://phr...@NOSPAM.invalid> wrote:
> tkp... at gmail.com writes:
> > RVDict= {'1': random.betavariate(1,1),     '2': random.expovariate(1), ...}
>
> This actually calls the functions random.betavariate, etc.  when
> initializing RVDict.  If you print out the contents of RVDict you'll see
> that each value in it is just a floating point number, not a callable.
>
> You want something like:
>
>   RVDict = {'1': lambda: random.betavariate(1,1),
>             '2': lambda: random.expovariate(1),     etc.

In Python 2.5, you can also write this as:

from functools import partial

RVDict = {'1': partial(random.betavariate,1,1),
          '2': partial(random.expovariate,1),
etc.


George



More information about the Python-list mailing list