adjusting python autoviv to take "+=1" increments

133 views Asked by At

I am using some common python autovivification code build dictionaries:

class autoviv(dict):
    """Implementation of perl's autovivification feature."""

    def __getitem__(self, item):  
        try:
            return dict.__getitem__(self, item)
        except KeyError:     
            value = self[item] = type(self)()
            return value

One thing I'd love to be able to is to increment values in the case where no key currently exists at the specified dictionary nesting level, using += notation like so:

d['a']+=1

Doing so will return the error:

TypeError: unsupported operand type(s) for +=: 'autoviv' and 'int'

To get around this I've built a step that checks whether the key exists before incrementing it, but I'd love to do away with that step if I could.

How should I modify the above autoviv() code to get this enhancement? I've googled and tried different approaches for a few hours but no joy.

Thanks for any advice!

1

There are 1 answers

1
Neil On

Autovivication is already in Python, inside of collections' defaultdict.

from collections import defaultdict


#Let's say we want to count every character
#  that occurs
text = "Let's implement autovivication!"
di = defaultdict(int)
for char in text:
    di[char] += 1
print(di)

#Another way of doing this is using a defualt string
#  (or default int, or whatever you want)
currentDict = {'bob':'password','mike':'12345'}
di = defaultdict(lambda:'unknown user', currentDict)
print(di['bob'])
print(di['sheryl'])

However, if you're trying to implement your own. You should assign your item and then get the reference to it.

def __getitem__(self, item):  
    try:
        return dict.__getitem__(self, item)
    except KeyError:
        value = self[item] = type(self)()        
        return dict.__getitem__(self, item)