# Using timeit in an interact without string formatting

I wanted the following to work, but it didn't. Anyone have an idea how to make it do so?

def T(n):
top = ceil(math.sqrt(n))
print top

@interact
def _(n=6739815371):
T(n)
timeit('T(n)')


def T(n):
top = ceil(math.sqrt(n))
print top

@interact
def _(n=6739815371):
T(n)
timeit('T(%s)'%n)


But I feel like the first thing did indeed work in the past (though I tried it with a Sage from 2010 to no avail).

I guess in some sense this is a silly question - 'T(n)' is a string, pure and simple. At the same time, in the command line

sage: def T(n):
....:         top = ceil(math.sqrt(n))
....:         print top
....:
sage: n=6739815371
sage: timeit('T(n)')
625 loops, best of 3: 5.96 µs per loop


and 'T(n)' is a string there too. So what is different about interact that this doesn't work (in Sage or the cell server)?

edit retag close merge delete

Sort by » oldest newest most voted As far as n is in the global namespace, the error message of your example is misleading. My example below gives the error message:

NameError: global name 'k' is not defined

def T(k):
top = ceil(math.sqrt(k))
print top

@interact
def _(k=6739815371):
timeit('T(k)')


So timeit apparently looks in the global namespace.

My first try was:

@interact
def _(k=6739815371):
global k
timeit('T(k)')


Traceback (most recent call last): def _(k=6739815371): File "", line 1, in <module> File "/tmp/tmpVWF0nv/___code___.py", line 8 @interact SyntaxError: name 'k' is local and global

So we have to outwit the @interact function:

@interact
def _(k0=6739815371):
global k
k = k0
timeit('T(k)')

more

I suspect it is some python idiosyncrasy. It is somehow not getting the variable n as defined in the function declaration. The following works (for some reason using n=n again didn't work, probably because n is defined globally to be some function):

def T(n):
top = ceil(math.sqrt(n))
print top

@interact
def _(k=6739815371):
T(k)
k = k
timeit('T(k)')

more