Skip to content
Advertisement

Generator function for file reading returning object type as regular function

I am trying to create a generator function to return the content of a .csv file row by row and while the generator function does seem to be iterable with me being able to loop over it with a for loop, when I print the object type of the generator function, instead of returning class ‘generator’, it returns class ‘function’. The generator function also has a memory size consistent with it being a generator function.

The function code:

    import sys, time
    
    start_time = time.time()
    def file_row_generator():
        for row in open('file.csv'):
            yield row
    print(file_row_generator)
    print(type(file_row_generator))
    print(sys.getsizeof(file_row_generator))
    l = []
    for row in file_row_generator():
        l.append(row)
    print(time.time() - start_time)

This returns the output:

<function file_row_generator at 0x00F3BC40>

<class ‘function’>

68

0.05980682373046875

Advertisement

Answer

file_row_generator is a function that returns a generator. Try print(file_row_generator()).

>>> def foo():
...     for i in range(3):
...             yield i
... 
>>> print(foo)
<function foo at 0x7fd3cedaa310>
>>> print(foo())
<generator object foo at 0x7fd3ced88660>
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement