I implemented a class in python which currently inherits from dict, but really, I don’t want it to. The main reason for inheriting is so that I can use the **kwargs construct for copying the contents into an argument list.
I presume python does some sort of iteration over the dictionary, but I can’t find any documentation.
Is this possible, and, if so, how?
Code sample just to make things clearer:
class MyThing():
def __init__(self):
self.dictionary = {}
thing = MyThing()
# code that causes thing.dictionary to be populated
somefunc(**thing)
results in this:
TypeError: somefunc() argument after ** must be a mapping, not instance
I went and read the python source, it seems to use the
keys()and__getitem__methodsFor the curious, If you use ** on a non-dict, CPython creates a new empty dict, and then calls
dict.update()to copy your object’s keys into the dict.Its probably to best to implement this as a subclass of
collections.MappingDue to the inheritance from Mapping, pretty much all dict methods are supported. Given the error message, I think you can argue that this should qualify in all implementations of python.
I’ve tried PyPy and it accepts the first version.