views:

337

answers:

4

I'm missing something very basic.

class C:
    def __init__(self):
        self.N = 100
        pass

    def f(self, param):
        print 'C.f -- param'
        for k in xrange(param):
            for i in xrange(self.N):
                for j in xrange(self.N):
                    a = float(i)/(1+float(j)) + float(i/self.N) ** float(j/self.N)

import cProfile

c = C()
cProfile.run('c.f(3)')

When I run the above code in IPython, I get:

NameError: name 'c' is not defined

What am I missing?

UPDATE the exact paste of my session is here: http://pastebin.com/f3e1b9946

UPDATE I didn't mention that the problem occurs in IPython, which (at it turns out) is the source of the problem

A: 

It works here. Please provide full traceback.

Also, provide the filename of your script.

nosklo
It doesn't work in IPython.
Denis Otkidach
+3  A: 

Although IPython is very handy, there is a lot of rare cases when it breaks working code or masks errors. So it's useful to try code in standard interpreter when you get such mystical errors.

Denis Otkidach
+4  A: 

While inside IPython, you can use the %prun magic function:

In [9]: %prun c.f(3)
C.f -- param
         3 function calls in 0.066 CPU seconds

   Ordered by: internal time

   ncalls  tottime  percall  cumtime  percall filename:lineno(function)
        1    0.066    0.066    0.066    0.066 <string>:6(f)
        1    0.000    0.000    0.066    0.066 <string>:1(<module>)
        1    0.000    0.000    0.000    0.000 {method 'disable' of '_lsprof.Profiler' objects}
unutbu
+3  A: 

Not the original poster's problem, but you can also get this same error if you are invoking cProfile.run() in something other than the __main__ namespace (from within a function or an import). In that case you need to use the following instead of the run() method:

cProfile.runctx("your code", globals(), locals())

Kudos to this post for helping me figure this out.

Von
Ah! Winner, I couldn’t believe there wasn’t way to profile from the shell without editing my code.
Paul D. Waite