0

Trying to create a metaclass that inherits from a parent class, that inherits from JSONEncoder. However, I am getting the following error:

TypeError: 'type' object is not iterable

Code looks like:

class ParentClass(JSONEncoder):
    def __init__(self, ...):
        ...
        ...

    def default(self, obj):
        try:
            return super().default(obj)
        except TypeError as exc:
            if 'not JSON serializable' in str(exc):
                return str(obj)
        raise

class AnotherClass():
    def __init__(...):
        ...

    def do_something(self, *args. **kwargs):
        attrs = {'field1': "FieldOne", 'field2': "FieldTwo"}
        ChildClass = type('ChildClass', tuple(ParentClass), attrs)
        ...

Is there anyway to make this ChildClass iterable using this method?

MeanwhileInHell
  • 6,780
  • 17
  • 57
  • 106
  • Does this answer your question? [Python: Make a dynamically created class (as in the class itself) iterable?](https://stackoverflow.com/questions/6970718/python-make-a-dynamically-created-class-as-in-the-class-itself-iterable) – Pravash Panigrahi Apr 27 '23 at 14:39
  • Yes, it is possible. Where does this "JSONEncoder" class come from? – jsbueno Apr 27 '23 at 14:58
  • 1
    @jsbueno It's part of the standard [json](https://docs.python.org/3/library/json.html#json.JSONEncoder) module. – Barmar Apr 27 '23 at 15:30
  • 1
    great! Since Python is a concise language, try to post complete working examples, imports included, when asking questions. Best regards! – jsbueno Apr 27 '23 at 18:11

1 Answers1

1

The error is due to the declaration of the tuple() method with ParentClass. The input to tuple() must be an iterable - change it to tuple([ParentClass]) or (ParentClass,) and the code will work.

AVManerikar
  • 169
  • 4