Any way for a function to refer to itself?

Joshua Marshall jmarshal at mathworks.com
Fri Feb 23 09:24:28 EST 2001


Emile van Sebille <emile at fenx.com> wrote:
> I'm not sure if it always plays nice, but you may try
> starting with:

>>>> def test():
>  "test function description"
>  import traceback
>  me = eval( traceback.extract_stack()[-1][2])
>  print "DocString: %s  functionName: %s " % (me.__doc__,
> me.__name__)


>>>> test()
> DocString: test function description  functionName: test

This doesn't do what was asked - it only works if test is defined in
the global namespace:

  def f():
      def test():
          "test function description"
          import traceback
          me = eval( traceback.extract_stack()[-1][2])
          print "DocString: %s  functionName: %s " % (me.__doc__, me.__name__)
  
      test()
  
  f()

Yields:

  Traceback (innermost last):
    File "fu.py", line 10, in ?
      f()
    File "fu.py", line 8, in f
      test()
    File "fu.py", line 5, in test
      me = eval( traceback.extract_stack()[-1][2])
    File "<string>", line 0, in ?
  NameError: test



More information about the Python-list mailing list