On Tue, 17 Apr 2001, Guido van Rossum wrote:
This is one of the reasons why I didn't want to add this to the 2.1 release at such a late point. I have no easy way to verify that this is always true, and in fact I have no idea what inspect.stack()[1][3] means. :-(
Would you have preferred to write
sys._getframe().f_back.f_code.co_name
? It's the same thing.
Well, that clears up one mystery. The rest of your explanation of why this is correct (as opposed to why this works in the two cases you've tried :-) is still completely opaque to me...
# Define the built-in object "help" to provide interactive help. class Helper: def __repr__(self): import inspect if inspect.stack()[1][3] == '?': # not called from a function self() return '' return '<Helper instance>' def __call__(self, arg=None): import pydoc pydoc.help(arg) __builtin__.help = Helper()
Why the strange check involving inspect.stack()? inspect.stack()[1][3] is the co_name of the parent frame. If we check that the __repr__ is not being requested by a function call, everything works perfectly in IDLE as well as the plain interpreter, and the helper object is still safe to pass around. Nothing breaks even if you say help(help).
--Guido van Rossum (home page: http://www.python.org/~guido/)