Search code examples
pythonperformancefor-loopdecoratorpython-decorators

workarounds for (pseudo-)decorating a for loop in python?


Of course I know this is not directly possible as in Python, as read in

Statement decorators

but still I would like to find a way to programmatically turn (on and off) a loop as:

for i in range(L[:]):
    # do stuff

into

for i in range(L[0:N])):
    # estimate how much time it
    # took to run the loop over a subset N element of the list
for i in range(L):
    # do stuff on the full list

Is there any pythonic way to do so?


Solution

  • Let's assume L is a list

    import time
    
    def timed_loop(L,subset,timeout):
        start = time.time()
        for i in L[0:subset]:
            do_something()
        stop = time.time()
        if stop-start < timeout:
            for i in L:
                do_something_else()