4

I am using a Python Mock object for a third-party package that needs to JSON serialize my mock. This means that I cannot change the invocation of json.dumps, so must use the solution here: https://stackoverflow.com/a/31207881/19643198

class FileItem(dict):
    def __init__(self, fname):
        dict.__init__(self, fname=fname)

f = FileItem('tasks.txt')
json.dumps(f)  #No need to change anything here

The only problem is that my object is not of class FileItem, but needs to be a MagicMock. This suggests multiple inheritance, so something like:

class FileItem(MagicMock, dict):
    def __init__(self):
        MagicMock.__init__(self) 
        dict.__init__(self)

Unfortunately, multiple inheritance from both dict and MagicMock seems not to work. In case this helps make this problem easier to solve, the third-party library does not need to deserialize or even use the JSON serialized representation of the MagicMock.

calmcc
  • 189
  • 7
  • you can't do that in python ;( There's a long-standing [bug](https://bugs.python.org/issue35111). Basically, you cannot encode a class if you don't control the encoder. Given that a proposed solution would require exactly two lines of code, it's a bit weird this hasn't been fixed yet. – gog Oct 07 '22 at 16:50
  • monekypatching the json module, as in https://stackoverflow.com/questions/57982946/how-to-register-implementation-of-abc-mutablemapping-as-a-dict-subclass, appears to be the only known "workaround" – gog Oct 07 '22 at 16:52

0 Answers0