0

I'd like to build a special dict class that has the option to export it's underlying dict as a whole (not just the individual items), i.e. something like this:

class CustomDict(dict):

    def export(self):
        return ???  # A dict instance

I know that I could simulate this behavior by simply building the export dict on the fly, or by storing the items in a separate class attribute in the first place, but I was wondering if there is a clean way of getting to the entire underlying dict directly. (Or am I overthinking this?)

Jongware
  • 22,200
  • 8
  • 54
  • 100
gmolau
  • 2,815
  • 1
  • 22
  • 45
  • Can you able to specify any example for the same. – Sanket Dec 29 '17 at 11:55
  • 1
    Well if it is a *subclass*, there is not really an "underlying" dict instance. You inherit all properties of the dict, except that the type reference is now `CustomDict`, and that some functions are overridden. – Willem Van Onsem Dec 29 '17 at 11:56
  • What about `return self`? – timgeb Dec 29 '17 at 12:12
  • (I was trying to make a point, any `CustomDict` is an instance of `dict`.) – timgeb Dec 29 '17 at 12:18
  • What's the point? Do you mean: to prevent people from using the subclass methods? Unfortunately that is not possible in Python without creating a new dictionary or a wrapper. – Bakuriu Dec 29 '17 at 12:22
  • @timgeb I'm a bit confused how this would work, it would mean there is no difference between using a `CustomDict` instance itself and calling `export()` on that instance, but what would happen if the histories of the instance itself and and the export diverge? Wouldn't I not just defer the copying of the dict to a later stage? – gmolau Dec 29 '17 at 12:26
  • @WillemVanOnsem I suspected that that is the case. That would mean that using `__getitem__` is as direct as I can get, right? – gmolau Dec 29 '17 at 12:28
  • @mxgx Well you never said `export` should produce a copy. Should it? – timgeb Dec 29 '17 at 13:31
  • @timgeb I wanted to detach the content of the dict from the reference to the dict, so that I could export the content and write it to a database or a file while still keeping the reference to the dict as a whole around. That is why I wanted to do this inside of the class, not just export the class instance itself. However, it seems that the only thing underlying even a dict subclass is the C struct itself and that `__getitem__` is the most direct access I can get. – gmolau Dec 29 '17 at 18:03

1 Answers1

0

There's no underlying dict instance. If you inherit from dict, CustomDict class is the dict class and has all dict's methods and properties. So what you want to do here is just pass the CustomDict instance wherever you wanted the dict to be exported to.

monomonedula
  • 606
  • 4
  • 17