brgn brgn - 24 days ago 8
Python Question

Import error when calling method from same module in timeit()

I want to measure the execution time of the Python method sayHello() using the method getExecutionTime(). They are both in a module and the getExecutionTime()-method should be callable from outside.

The code looks like this:

def getExecutionTime():
t = timeit.Timer("sayHello", "from __main__ import sayHello")
return t.timeit(2)

def sayHello():
print("Hello")


I keep getting an ImportError saying: "Cannot import name sayHello in File ..."

I added the scope argument (
"from __main__ import sayHello"
) to the Timer constructor to make the sayHello() method available within the timeit scope.

Note: I don't want to call getExecutionTime() in the main part of this method, I want to that method from somewhere else.

Can anyone help?
Thanks.

Answer Source

I have a file that is literally this:

import timeit

def getExecutionTime():
    t = timeit.Timer("sayHello()", "from __main__ import sayHello")
    return t.timeit(2)

def sayHello():
    print("Hello")

print(getExecutionTime())

When run, it prints Hello twice and then the execution time. (Also note that it's sayHello() rather than sayHello in the Timer set up).

Are you running this from within an IDE? From the command line & IDLE it works for me, under both Python 2.7 & 3.2.