tags:

views:

50

answers:

1

Hello everyone,
I am trying to pass current object reference i.e. self to the Timer class of timeit module but somehow i am not getting it how to do it. I tried to find it in timeit documentation but i could not find it. I have attached my code with this question.

from timeit import Timer
import time  
import math

class PollingDemo(Thread):

    def __init__(self):
        pass

    def looper(self):

        while 1:
            try:
                T = Timer("self.my_func()")
                #T = Timer("polling.my_func()", "from __main__ import polling")
                time_elapsed = T.timeit(1)

                if math.ceil(time_elapsed) == 1:
                    print "Process is sleeped for 1 sec"
                    time.sleep(1)

            except KeyboardInterrupt:
                return

    def my_func(self):
        pass

if __name__ == '__main__':

    polling = PollingDemo()
    polling.looper()  

In this example i have tried to call my_func() method of PollingDemo class through Timer class timeit() method but i am getting "NameError: global name 'self' is not defined" error. if we tried to access that object through main it works (Next commented line works perfectly). Can someone please why is this behavior so.
Thanks in advance.

+3  A: 

Don't use a string, Timer also accepts callables, so pass a reference bound to self directly, i.e.

T = Timer(self.my_func)

(just the reference, don't call it).

If you need more complex setup, again wrap it in a function or method and pass that method.

Ivo van der Wijk
It worked perfectly.. Thanks.. :)
Rupesh Chavan
Ivo it would be great if you can tell me what happen internally when we pass string to Timer class or any reference about it will be highly appreciated. - Thanks
Rupesh Chavan
The string is evaluated in its own isolated context (you don't get to supply locals or globals). 'self' will simply not be available. This means strings (optionally with their setup string) must be self contained and define/introduce everything that's necessary.
Ivo van der Wijk
Hmm, that was nice explaination. thanks a lot.. :)
Rupesh Chavan