0

Say I have a function:

def foo():
    """foo docstring"""
    print(foo.__doc__)

How can I write this, without using the function name foo within the print function?

Please note I've read through this similar question, which allows access to the name of a function as a string, but as far as I can see does not give access to the function itself.

John Forbes
  • 1,248
  • 14
  • 19
  • And... why? What utility is there is a mechanism for a function not to know its own name? – Stephen Rauch Sep 13 '18 at 04:47
  • @StephenRauch quite simply because a function is an object and just like other objects it doesn't really have a name. If after `foo` definition you add `bar = foo; foo = None; bar()`, then you will not get the expected result. – bruno desthuilliers Sep 13 '18 at 09:45

1 Answers1

1

The answer was much simpler than I expected. To access the function itself instead of just the name, apply eval() to the name.

import inspect

def foo():
    """zxy"""
    print(fself().__doc__)

def fself():
    """returns parent function when called"""
    return eval(inspect.stack()[1][3])

def bar():
    """abcdefg"""
    print(fself().__doc__)

bar()
foo()

This code produces:

>abcdefg
>zxy

The great thing is I can now use this as a module and access fself in other scripts.

John Forbes
  • 1,248
  • 14
  • 19