I wrote a class (see below) for a automatically updating dictionary.
For example let -
def xsq(x):
return(x*x)
D = auto_update_dict(xsq)
D[2] calls xsq and returns 4
call D[2] and xsq is not called since the previous call has called xsq
and placed
the result in the dictionary. Again 4 is returned.
When I use auto_update_dict in subs it does not work since since if the
argument
in subs is a dict the first thing subs does is to save D.items() and it
never works
with D again so that the state of D.items() is frozen for the sub call
and the D.items()
and D is never updated during the call to sub.
The purpose of the auto_update_dict is to insure that one never has to
generate
a dictionary entry more than once so that time consuming calls to complex
functions are not repeated.
Can anyone suggest a work around to the problem with subs and dictionaries?
class auto_update_dict(dict):
"""
auto_update_dict creats entries to a dictionary on the fly. When the
dictionary is called and the key used is not one of the existing keys
The function self.f_update(key) is called to evaluate the key. The
result is then added to the dictionary so that self.f_update is not
used to evaluate the same key again.
The __init__ is used to input self.f_update for a given dictionary.
"""
def __init__(self, f_update, instance=None):
self.f_update = f_update
self.instance = instance
self._dict = {}
def __getitem__(self, key):
try:
return dict.__getitem__(self, key)
except KeyError:
try:
if self.instance is None:
f_key = self.f_update(key)
else:
f_key = self.f_update(self.instance,key)
self[key] = f_key
dict.__setitem__(self, key, f_key)
return dict.__getitem__(self, key)
except ValueError:
raise ValueError('"f_update(' + str(key) + ')" not
defined '
+ 'for key')
--
You received this message because you are subscribed to the Google Groups
"sympy" group.
To unsubscribe from this group and stop receiving emails from it, send an email
to sympy+unsubscr...@googlegroups.com.
To post to this group, send email to sympy@googlegroups.com.
Visit this group at http://groups.google.com/group/sympy?hl=en-US.
For more options, visit https://groups.google.com/groups/opt_out.