Simple Object assignment giving me errors

Jerry Hill malaclypse2 at
Wed Feb 12 23:09:00 CET 2014

On Wed, Feb 12, 2014 at 4:42 PM, Nir <nirchernia at> wrote:
> If this makes sense to you, great. I am trying to break it down so that I can make sense of it. As you mentioned self["name"] = filename doesn't work unless I built a class to handle it. I guess my question then, is how is the class handling it in this code? If you can show me by stripping it down to the bare minimum or write an example that would be awesome.

This example works because the UserDict object being used in this code
was built to handle it.  The UserDict class in the standard library
does a lot more than the little snippet you had in your original code.
 Your original code would work if you did the same thing, like this:

from collections import UserDict

class FileInfo(UserDict):
        def __init__(self, filename=None):
                self["name"] = filename

jeez = FileInfo("yo")

(If you're using Python 2, then the first line should be "from
UserDict import UserDict" instead).

You can take a look at the source code for the userDict class here:
.  In that class, the code responsible for handling the bracketed name
lookup (i.e., self["name"]), is in the __getitem__ and __setitem__
methods (and peripherally in __delitem__, __len__ and __contains__)


More information about the Python-list mailing list