2

I just extended the default behavior of setitem method of a dict to look like this

class SafeSwapDict(dict):
    def __setitem__(self, key, value):
        if isinstance(key, collections.Hashable):
            super(SafeSwapDict, self).__setitem__(key, value)
        else return False
    return True

When i'm calling that method i would like to get those return values but i cannot seem to find a turnaround since

a = SafeSwapDict()
print a['1'] =  132

won't work (it expects = to be ==)

Also

a = SafeSwapDict()
w = a['1'] = 132
print w 

will output 132 (it will first execute the right hand side of the statement (a['1'] = 132) and then copy the value into w, not the method's return value )

The following works, but it is not really useful (why overload an operator if you cannot use it as intended?)

print dict_out.__setitem__(1, 132)

Any other suggestions? P.S. I'm not allowed to use exception handling :)

1 Answers1

2

In your specific example, dict returns False only if your key is not Hashable. In any other case, the assignement works.

Just like when you make any assignement some_var = 2, you don't need to test if some_var really is 2, because it is.

In the case of dict, an invalid key (such as a list) will fail and you'll be notified:

>>> some_dict = {}
>>> some_dict[[0]] = 42   #the key is a list [0], unhashable
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'list'

In summary, you don't need to test the success of your assignement, because it never silently fails.

njzk2
  • 38,969
  • 7
  • 69
  • 107