storing references instead of copies in a dictionary

bruno.desthuilliers at gmail.com bruno.desthuilliers at gmail.com
Fri Jul 18 08:13:17 EDT 2008


On 17 juil, 15:56, mk <mrk... at gmail.com> wrote:
> Calvin Spealman wrote:
> > To your actual problem... Why do you wanna do this anyway? If you want
> > to change the function in the dictionary, why don't you simply define
> > the functions you'll want to use, and change the one you have bound to
> > the key in the dictionary when you want to change it? In other words,
> > define them all at once, and then just d['1'] = new_f1. What is wrong
> > with that?
>
> Well, basically nothing except I need to remember I have to do that.
>
> Suppose one does that frequently in a program. It becomes tedious. I
> think I will define some helper function then:
>
>  >>> def helper(fundict, newfun):
> ...     fundict[newfun.func_name] = newfun
> ...
>
> _If_ there were some shorter and still "proper" way to do it, I'd use
> it.

You're halfway there.

from functools import partial

callbacks = {}
register_callback = partial(helper, callbacks)

@register_callback
def f1(arg):
    print "f1", arg

callbacks['f1']('ok')

@register_callback
def f1(arg):
    print "new f1", arg

callbacks['f1']('ok')




More information about the Python-list mailing list