Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting the return value of __setitem__() and length of dictionary

Tags:

python

I have the following dictionary:

class Only5Items(dict):
    def __setitem__(self, key, value):
        if len(self) < 5:
            super(Only5Items, self).__setitem__(key, value)

I want to return true, if I success to add an item. Any ideas?

I'll explain it a little more. For example:

items = Only5Items()
items["hi1"] = "asdf1"
items["hi2"] = "asdf2"
items["hi3"] = "asdf3"
items["hi4"] = "asdf4"
items["hi5"] = "asdf5"
items["hi6"] = "asdf6"

items["hi6"] = "asdf6" won't insert. And i want to print a message about it.

edit: len(self) works. And to be more specific, i don't want to print a message about it, i want to return true/false if i success to add it. Something external to the class.

like image 282
Weiner Nir Avatar asked Nov 01 '25 13:11

Weiner Nir


1 Answers

Assignment doesn't have a return value in Python and the return value of __setitem__() is ignored. Generally, you'd want to raise an exception instead:

class Only5Items(dict):

    def __setitem__(self, key, value):
        if len(self) < 5 or key in self:   # allow reassignment of existing key
            return super(Only5Items, self).__setitem__(key, value)
        raise KeyError("maximum number of items (5) exceeded")

Then your client code can catch the exception:

items = Only5Items(hi1="asdf1", hi2="asdf2", hi3="asdf3", hi4="asdf4", hi5="asdf5")
try:
    items["hi6"] = "asdf6"
except KeyError as e:
    print(e)

If you want to return True/False then you have to write your own assignment method that can return a value:

class Only5Items(dict):

    def __setitem__(self, key, value):
        if len(self) < 5 or key in self:   # allow reassignment of existing key
            return super(Only5Items, self).__setitem__(key, value)
        raise KeyError("maximum number of items (5) exceeded")

    def did_set(self, key, value):
        try:
            self[key] = value
        except KeyError:
            return False
        return True

Then you'd use it like this:

if not items.did_set("hi6", "asdf6"):
    print "couldn't set key 'hi6', dictionary is probably full"

You probably also want to override setdefault() to check the number of items too... also, it'd be nice (and pretty easy) to pass in the maximum number when you instantiate the class instead of hard-coding it to 5.

like image 87
kindall Avatar answered Nov 03 '25 03:11

kindall



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!