Reputation: 18725
I'm trying to write name of the current executed function. But it does not work properly.
When I put 'print inspect.stack()[0][3]'
after the def func()
, it works, but when I try to put this command after the if, it prints nothing.
import inspect
debug = True
def debug():
print inspect.stack()[0][3]
if debug==True:
print "test"
print inspect.stack()[0][3]
debug()
returns 'debug'
but it should return
'debug'\n'test'\n'debug'
Where is the problem?
Upvotes: 1
Views: 1546
Reputation: 35891
When you define the function:
def debug():
you are loosing the last reference to the previously created variable debug
from the global scope. You redefine the debug
variable from being a boolean holding True
to a function reference. So the condition debug==True
is not met (because debug
is a function now, not a boolean). And thus only the first print
statement works (see an illustrative demo).
This will work as intended, for example:
import inspect
debug = True
def f():
print inspect.stack()[0][3]
if debug==True:
print "test"
print inspect.stack()[0][3]
f()
This is a common mistake in Python, especially from people used to other languages, in which function names are treated in a special way. In Python they are not - after you define a function, you can use its name as any other variable. Which has many advantages, but as seen here sometimes can be confusing.
Upvotes: 1
Reputation: 129
In python 3 and hight you need to use print () if. It becomes a syntax error and won't print any thing if you don't have the ()
Upvotes: 0