Home > Back-end >  Why does this code to call a function for a period of time freeze?
Why does this code to call a function for a period of time freeze?

Time:07-18

from time import time

def multiply(n1, n2):
    return n1 * n2

# Causes Python to freeze (CASE 1)
def not_working_1_timed_exec(func, sec, *args, **kwargs):
    start = time()
    while time() - start < sec:
        yield func(*args, **kwargs)

# print(list(not_working_1_timed_exec(multiply, 5, 2, 5)))

# Causes Python to freeze (CASE 2)
def not_working_2_timed_exec(func, sec, *args, **kwargs):
    start = time()
    ret = []
    while time() - start < sec:
        ret.append(func(*args, **kwargs))
    return ret

# print(list(not_working_2_timed_exec(multiply, 5, 2, 5)))

# Works
def timed_exec(func, sec, *args, **kwargs):
    start = time()
    while time() - start < sec:
        print('hello world') # MAKES IT WORK
        yield func(*args, **kwargs)

print(list(timed_exec(multiply, 5, 2, 5)))

The goal is to write a simple function that accepts a function as a parameter and calls it for a period of time

I would love to know why it does not work, and why print() makes the function work ?

CodePudding user response:

So, as discussed in the comments, this is not a bug in Python at all, it's a deficiency in IDLE's (which is what OP used) output printing, which chokes/seems to hang on a very long line (i.e. the result of the fast not_working version).

Making the function slower makes things seem to work, since there's no longer that much output to format.

CodePudding user response:

IDLE's output formatting probably chokes on the 118 megabyte string that is the stringified output of the list. (The function that spams "hello world" manages to call multiply 1,281,433 times, for an output of about 5.1 megabytes.)

  • Related