storing references instead of copies in a dictionary

Calvin Spealman ironfroggy at gmail.com
Thu Jul 17 14:30:13 CEST 2008


On Thu, Jul 17, 2008 at 7:45 AM, mk <mrkafk at gmail.com> wrote:
> Hello everyone,
>
> I'm storing functions in a dictionary (this is basically for cooking up my
> own fancy schmancy callback scheme, mainly for learning purpose):
>
>>>> def f2(arg):
> ...     return "f2 " + arg
> ...
>>>>
>>>> def f1(arg):
> ...     return "f1" + arg
> ...
>
>>>> a={'1': f1, '2': f2}
>>>>
>>>> [ x[1](x[0]) for x in a.items() ]
> ['f11', 'f2 2']
>
> Well, neat. Except if I change function definitions now, old functions are
> called. And rightly:
>
> {'1': <function f1 at 0xb7f0ba04>, '2': <function f2 at 0xb7f0b9cc>}
>>>> f1
> <function f1 at 0xb7f0ba04>
>>>>
>>>> def f1(arg):
> ...     return "NEW f1 " + arg
> ...
>>>> f1
> <function f1 at 0xb7f0b994>
>
> The address of function f1 has obviously changed on redefinition.
>
> Storing value copies in a dictionary on assignment is a reasonable default
> behaviour.
>
> However, in this particular case I need to specifically store _references to
> objects_ (e.g. f1 function), or should I say _labels_ (leading to objects)?
>
> Of course, I can basically update the dictionary with a new function
> definition.
>
> But I wonder, is there not a way _in general_ to specifically store
> references to functions/variables/first-class objects instead of copies in a
> dictionary?

As was pointed out already, this is a basic misunderstanding of
assignment, which is common with people learning Python.

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?

For completeness:

def new_f1(arg):
    return "NEW f1 " + arg
f1.func_code = new_f1.func_code

Don't use that unless you really have to and I nearly promise that you don't.

-- 
Read my blog! I depend on your acceptance of my opinion! I am interesting!
http://ironfroggy-code.blogspot.com/



More information about the Python-list mailing list