1

I want to know how to access a function from within it without naming it directly.

def fact(n):
    this = # some code, where we don't use the name "fact"
    print(fact == this) # True
    if n < 1:
        return 1
    return n * this(n-1)

The code above should behave exactly like:

def fact(n):
    if n < 1:
        return 1
    return n * fact(n-1)

Does anyone have any ideas?

EDIT:

My question is different from Determine function name from within that function (without using traceback). I need fact == this in the code above to return True.

EDIT2:

@ksbg's answer is a good one, but consider the folowing code:

from inspect import stack, currentframe

def a():
    def a():
        f_name = stack()[0][3]  # Look up the function name as a string
        this = currentframe().f_back.f_globals[f_name]
        print(a == this)
    a()

a() # False

In this case it wont work as expected.

ibodi
  • 1,543
  • 3
  • 21
  • 40

1 Answers1

4

This can be done by inspecting the stack trace. First we look up the function name as a string, and then we go back one frame (or level), and get the function from the module's globals:

from inspect import stack, currentframe

f_name = stack()[0][3]  # Look up the function name as a string
this = currentframe().f_back.f_globals[f_name]  # Go back one level (to enter module level) and load the function from the globals

However, I don't consider this good practice, and if possible, I would avoid doing that. As already pointed out in comments to your question, doing this without inspecting the stack trace isn't possible in Python.

ksbg
  • 3,214
  • 1
  • 22
  • 35