Serialize a Generator in Python

Simply inherit from the list class, and override the __iter__ method. A great example, from SO:

import json

def gen():
    yield 20
    yield 30
    yield 40

class StreamArray(list):
    def __iter__(self):
        return gen()

a = [1,2,3]
b = StreamArray()

print(json.dumps([1,a,b]))
Advertisements

2 thoughts on “Serialize a Generator in Python

  1. Pingback: kathirbesant

Comments are closed.