Noah
Noah

Reputation: 23

TypeError: 'generator' object is not callable.

def lines(file):
    for line in file:
        yield line
    yield '\n'

def blocks(file):
    block = []
    for line in lines(file):
        if line.strip():
            block.append(line)
        elif block:
            yield ''.join(block).strip()
            block = []


with open(r'test_input.txt', 'r') as f:
    lines = lines(f)
    file = blocks(lines)
    for line in file:
        print(line)

I got this error message:

TypeError: 'generator' object is not callable

I don't know what happened. Does it because generator in python3.6 is different from 2.X?

Upvotes: 2

Views: 9193

Answers (2)

Blckknght
Blckknght

Reputation: 104842

Your issue is caused by this line:

lines = lines(f)

With this assignment, you're overwriting the lines generator function with its own return value. That means that when blocks tries to call lines again (which seems a little buggy to me, but not the main issue), it gets the generator object instead of the function it expected.

Pick a different name for the assignment, or just pass f to blocks, since it will call lines itself.

Upvotes: 2

Loïc G.
Loïc G.

Reputation: 3157

Your problem is not related to Python3. This error exists with Python 2.6.

I do not know exactly what you try to do but your code do not throws error replacing blocks function with :

def blocks(file):
    block = []
    for line in file:  # here, replace lines(file) with file
        if line.strip():
            block.append(line)
        elif block:
            yield ''.join(block).strip()
            block = []

However, I don't understand what you try to do with lines()

If this answer is not suitable to you, I encourage you to edit your question with more detail on what the functions are supposed to do.

Upvotes: 0

Related Questions