Member function to turn class into dict I'm working on a project where I often want to turn class instances into dictionaries to write them to MongoDB. I'd like some feedback on the following:

def getDict(self):
    self.dict = dict()
    for key in self.__dict__.keys():
        if key not in self.NOT_INCLUDE: # class variable
            try:
                self.dict[key] = getattr(getattr(self, key), "getDict")()
            except:
                self.dict[key] = getattr(self, key)
    return self.dict


This will turn any class with getDict into a dictionary, including any instance properties that themselves have a getDict method.

Also please let me know if there's an easy way to do this with the standard library that I missed.
What are you Returning

This function is adding a new member variable, self.dict. Presumably you want to just return a new temporary variable. Also, dict() is actually less efficient than {}, so you might want to start with:

member_dict = {} # or however you want to name it


Iterating over a Dict

In python, iterating over a dict is the same as iterating over the keys, so we can just save that step:

for key in self.__dict__:


But really, you don't just want the keys, you want the values too, so let's just get both:

for key, val in self.__dict__.items():


getattr

Use getattr() only for variable attribute names. Otherwise, just reference the attribute directly. getattr(x, 'getDict')() is more verbose and harder to parse than x.getDict().

Catching Exceptions

Don't just catch every exception - catch the one you expect to see. In this case, AttributeError:

member_dict = {}
for key, val in self.__dict__.items():
    if key not in self.NOT_INCLUDE:
        try:
            member_dict[key] = val.getDict()
        except AttributeError:
            member_dict[key] = val
return member_dict


Add a Free Function

def getDictIfExists(obj):
     try:
         return obj.getDict()
     except AttributeError:
         return obj


This lets you write the whole thing as a generator expression

return {key: getDictIfExists(val)
        for key, val in self.__dict__.items()
        if key not in self.NOT_INCLUDE}