[Tutor] help with a class
hugo.yoshi at gmail.com
Wed Aug 24 21:21:30 CEST 2011
On Wed, Aug 24, 2011 at 8:34 PM, John <washakie at gmail.com> wrote:
> Hello, I have a class that has an attribute that is a dict which I
> fill with more dicts. I've created a function to return those
> dictionaries if a key is provide, otherwise, it returns the 'default'
> I have the following methods (see below), it seems the update_options
> method is fine, but I'm not sure about the override_options method...
> and for that matter, I'm not sure this is the best approach overall...
> any comments, critiques?
You've identified the problem point correctly, override_options will
not work as expected. What it does is:
1) retrieve a dict through _get_from_queue()
2) point the name old_options toward that dict
3) point the name old_options toward a different dict (the one that
options points to)
as you can see, the dict that is inside self.run_queue isn't actually
changed just by making old_options point towards the new dict. What
you need to do is actually assign the new dict to the place in the
queue, like so:
self.run_queue[queue_key] = options
of course, this will also just create a new entry in the dict if there
wasn't one previously, which isn't exactly an 'override.' So if you
want that behavior, check for it and raise an error by yourself.
One other thing, inside _get_from_queue(). If a key isn't present in a
dictionary, you generally raise a KeyError, not a ValueError. A
ValueError is for when a function argument is of the correct type, but
has an inappropriate value, and the error isn't more accurately
described by another exception like an IndexError. For example,
math.sqrt(-1) raises a ValueError because negative numbers don't make
sense for square roots, even though the argument is of the correct
type (yes, the math module doesn't have support for imaginary numbers
built in, even though the language does ಠ_ಠ There is cmath though).
More information about the Tutor