I'm Jerry Wohlgemuth.

about me

Using `UserDict` in Py2 and Py3


If you want to create a dict like object using UserDict in Python 2 and 3, there's a couple of things to keep in mind.

  1. UserDict has moved to the collections module in Py3.
  2. UserDict in Py2 is an "old-style" class. This will cause problems if using super.

I ran into a couple issues trying to create a dict like object that is kept in sync with a yaml file. Here's how I made it compatible with both Python versions (not the full implementation here):

from UserDict import UserDict
except ImportError:
from collections import UserDict

import yaml

class YamlDict(UserDict, object):
def update(*args, **kwargs):
super(YamlDict, self).update(*args, **kwargs)

def _save(self):
with open('path_to_file', 'w+') as f:

Mixing in object allows you to use super.