Say I have a dictionary that contains complex classes that need to be loaded and unloaded in a special way. (Not especially special, just outside the bounds of this question.) Should I gracefully subclass the built-in dict like this:
class ExampleClass(dict):
def __str__(self):
return 'ExampleClass; '+dict.__str__(self)
@classmethod
def loads(cls, string):
<load object from string here>
def dumps(self):
<dump object here>
Or do something like this:
def load_special_structure(string):
<load object from code here>
def dump_special_structure(obj):
<dump object here>
That's all the extra functionality I need. It's not too pythonic to have to use a special imported method to dump and load it, but subclassing a dictionary isn't either. On the usage perspective, being able to import that class, load it from a string and use it like a dictionary is really useful.
Best Answer
In general, in Python I favor using functions over subclassing internal classes. In the end, if you write your
String -> dict
method, you end up working with adict
, pure as the driven snow. Just put your functions in a sensible module and import them only where needed; this will also encourage you not to import the functions everywhere, which will help you out by keeping the IO separated from your logic.