6

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.

  • What are the expected return types of the functions/methods? Always dict or always ExampleClass? – exhuma Aug 14 '18 at 19:33
5

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 a dict, 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.

  • Sounds interesting. The thing is, the entire module actively deals with loading and unloading objects (i.e. all classes are functional, but they all implement a method of loading and unloading) and it's better if I can tell that its type is of that special kind. Something else less important is the fact that what it contains is custom objects containing custom objects, but in the end, it's just an arbitrary dictionary that, after many loads() and dumps() methods, requires importing a module just to load and dump it, which kind of defeats the purpose of Object Oriented Programming. – noɥʇʎԀʎzɐɹƆ Jul 10 '15 at 17:49
  • 1
    Why would you load and dump many times? That seems like something that should happen only at the boundaries of your system. Also, if you need to carry information about the kind of object you have, I'd say you do need a class -- but I don't think it should be a subclass of dict. – asthasr Jul 10 '15 at 17:55
  • Not many times, but I have to dump and load it for each server instance, and I don't wanna do from utils.dataprocessing import load_blablabla, dump_blablabla – noɥʇʎԀʎzɐɹƆ Jul 10 '15 at 18:00

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.