Vesa Apaja
Vesa Apaja

Reputation: 3

A working generator function without "yield"

In Python 3.5 this returns a generator, but there is no yield:

def square(n):
    return (x**2 for x in range(n))

print(square) 
# <function square at 0x7f1ad0990f28>
print(square(10))
# <generator object square.<locals>.<genexpr> at 0x7f1ad08e0af0>

Apart from being more apparently a generator function, is there a reason to prefer a yield'ed version, like

def square(n):
    for x in range(n): yield x**2

print(square)
# <function square at 0x7f1ac413ed90>
print(square(10))
# <generator object square at 0x7f1ad08e0d58>

To me they seem to work identically.

Upvotes: 0

Views: 812

Answers (1)

Martijn Pieters
Martijn Pieters

Reputation: 1124758

Your function is indeed not a generator, but this expression is:

(x**2 for x in range(n))

It is a generator expression, see the reference documentation.

Both a generator expression and a function body containing yield result in a generator object. Since both are an object, you can pass it around and return one from a function.

A generator function and the equivalent generator expression are functionally exactly the same. They produce the same bytecode. Pick the one you feel is more readable for your use case.

Upvotes: 6

Related Questions