python - Trying to create generator object but getting function object that doesn't respond to generator calls -


i'm trying write infinite generator repeat every positive integer n times. example, if create f = inf_repeat(3), printing output of f 10 times result in:

1 1 1 2 2 2 3 3 3 4 

i close not quite there. here's i've got:

    # courtesy of http://stackoverflow.com/questions/279561/what-is-the-python-equivalent-of-static-variables-inside-a-function     # generator yields items instead of returning list     def static_var(varname, value):         def decorate(func):             setattr(func, varname, value)             return func         return decorate      def inf_repeat(k):         count_limit = k         @static_var("counter", 0)         @static_var("number", 0)         def func():             while true:                 if  func.counter == count_limit:                     func.counter = 0                     func.number += 1                 func.counter += 1                 yield func.number         return func 

my problem doesn't behave entirely iterator. following commands work:

f3 = inf_repeat(3) print next(f3()) 

but it's irritating have call f3 parens. i'd able use standard iterator syntax i've seen, such as:

print(f3.next()) 

and

new_list = [iter(f3)]*5 

what need modify in function point? looking @ variety of generator tutorials, seemed yield sufficient create generator, that's not case.

also have no objective using module. checked itertools maybe missed want without code?

you need call generator object (what called f3) @ point. can call when create it:

f3 = inf_repeat(3)() 

or inside inf_repeat

# change last line return func() 

putting yield in function makes generator function --- is, function that, when called, returns generator. if want generator, need call generator function @ point.

incidentally, implementation needlessly complex. can desired behavior more without decorators , nested functions:

def inf_repeat(k):     number = k     while true:         yield number // k         number += 1 

then:

>>> list(itertools.islice(inf_repeat(3), 10)) [1, 1, 1, 2, 2, 2, 3, 3, 3, 4] >>> list(itertools.islice(inf_repeat(4), 13)) [1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4] 

Comments