Search code examples
pythonpython-2.7dictionaryoverridingbuilt-in-types

Override built-in classes, in particular, dictionary class


I've never really liked the way the dictionary class is converted into a string so I wrote a subclass which overrides the __repr__ method (this method uses tabs to representing the level of nesting in the dictionary, mostly because I have some dictionaries which can be very big and end up myDic['a']['b']['c']['d'] = someObject).

It works fine, but it doesn't allow me to use the {} syntax to make my dictionaries.

Is it possible to override the dict class such that I can use the {} syntax to make my own custom dictionaries?

I am using python 2.6/2.7.


Solution

  • You can't override the {} syntax. You have to explicitly construct your variables using the class name.

    If you just want it printed more nicely, would using pprint.pprint suffice?