Search code examples
pythonmoduleeoltimeit

Timeit module is rejecting print("\n") statements


I am trying to run the following code example

from timeit import timeit as t 

setup = '''
import time
from multiprocessing import Pool

def square(x):
    square = x * x
    time.sleep(1)
    return square
'''
case01 = '''
def caso01(): 

    print("\nPART 1")
    
    starttime = time.time()
    pool = Pool(4)
    pool.map(square, range(0, 5))
    pool.close()
    endtime1 = time.time()
    print(f"Time taken {endtime1-starttime} seconds")
    return None
'''
def main():
    print( t(setup=setup,stmt=case01,number=100) )
    return None
main()

and I get always the same error:

File "/usr/lib/python3.8/timeit.py", line 233, in timeit
  return Timer(stmt, setup, timer, globals).timeit(number)
File "/usr/lib/python3.8/timeit.py", line 122, in __init__
  compile(stmtprefix + stmt, dummy_src_name, "exec")
File "<timeit-src>", line 16
  print("

I figured out that removing "\n" from the print sentence the problem disapears. Is it not posible to use "\n" at all with Timeit module? What am I missing?

Thanks

PS: using Python 3 on linux machine


Solution

  • You need to add a leading backslash (\) to escape the \n because it is being decoded at runtime.

    case01 = '''
    def caso01(): 
    
        print("\\nPART 1")
        
        starttime = time.time()
        pool = Pool(4)
        pool.map(square, range(0, 5))
        pool.close()
        endtime1 = time.time()
        print(f"Time taken {endtime1-starttime} seconds")
        return None
    '''