Python How to initialize a Reader object in a class definition

I want to create a singleton class that collects data from a csv file, and for this it needs to have a data member of type DictReader; but I'm not sure how to initialize this member in the class definition, since it can be initialized as follows:

with open('sourceFile.csv') as source:
    reader = csv.DictReader(source)

Since Python will not allow you to declare variables without initialization, I need to know how I can initialize a reader object in the Singleton class.

+4
source share
1 answer

You are looking for something like:

class MySingleton(object):
    def __init__(self, source):
        self.my_reader = DictReader(source)


if __name__ == '__main__':
    singleton = MySingleton(sourcefile)
    for row in singleton.my_reader:
        # do stuff
+1
source

All Articles