code-life balance
code-life balance

Reputation: 319

How to check elements created by generator when debugging a python project?

I use PyCharm to realize a program which is aimed to generate primes. Code like this:

def _odd_iter():
    n = 1
    while True:
        yield n
        n = n + 2


def _not_divisible(n):
    return lambda x: x % n > 0


def primes():
    it = _odd_iter()
    yield 2
    while True:
        i = next(it)
        yield i
        it = filter(_not_divisible, it) # !!!!!!!!!!don't know how it works!!!!!!!!!!

for n in primes():
    if n < 1000:
        print(n)
    else:
        break

For me the annotated code is obscure, I dont know how it works and whether it is right, so I add a breakpoint on it and determine to debug. But it is a generator, I cannot see the detail numbers. What can I do?

Upvotes: 0

Views: 805

Answers (1)

GIZ
GIZ

Reputation: 4643

filter(function or None, iterable) --> filter object

Return an iterator yielding those items of iterable for which function(item) is true. If function is None, return the items that are true.

You can't see the details because it returns an iterable object, do this to see what it returns:

it = list(filter(_not_divisible, it)) # or next(filter(...))

Upvotes: 1

Related Questions