storing references instead of copies in a dictionary

bgeddy bgeddy at home.havin.a.break
Thu Jul 17 16:47:34 CEST 2008


mk 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. If not, no big deal.
> 
>> 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.
> 
> I promise I won't use it. :-) It seems like a 'wrong thing to do'.
> 
> 

Well it's probably totally "non pythonic" but this does what you want:

def f2(arg):
     return "f2 "+arg

def f1(arg):
     return "f1 "+arg

a={"1":"f1","2":"f2"}
print [eval(x[1])(x[0]) for x in a.items()]
def f2(arg):
     return "New f2 "+arg
print [eval(x[1])(x[0]) for x in a.items()]

Don't know if this is any use to you..




More information about the Python-list mailing list