I'm trying to create a class variable and assign the name of the function calling that class, which is being imported from a separate .py. But nothing seems to be working.
File 1 (caller)
from file2 import A
def func(): # <-- Function name I want to get
a = A() # Initializing class A
File 2 (where class A is)
class A:
func_name = ... # <-- Where I would like to get the caller function name (func)
def __init__(self):
...
I've tried:
- inspect.stack()[1][3]
- inspect.currentframe().f_back.f_code.co_name
- inspect.getframeinfo(sys._getframe(1))[2]
- sys._getframe(1).f_code.co_name
But so far all I'm getting is either: <module>
or <frozen importlib._bootstrap>
, so I'm wondering if it's possible to get the caller's function name if the class is being imported in a separate file.
I'm trying to create a class variable and assign the name of the function calling that class, which is being imported from a separate .py. But nothing seems to be working.
File 1 (caller)
from file2 import A
def func(): # <-- Function name I want to get
a = A() # Initializing class A
File 2 (where class A is)
class A:
func_name = ... # <-- Where I would like to get the caller function name (func)
def __init__(self):
...
I've tried:
- inspect.stack()[1][3]
- inspect.currentframe().f_back.f_code.co_name
- inspect.getframeinfo(sys._getframe(1))[2]
- sys._getframe(1).f_code.co_name
But so far all I'm getting is either: <module>
or <frozen importlib._bootstrap>
, so I'm wondering if it's possible to get the caller's function name if the class is being imported in a separate file.
1 Answer
Reset to default 1Try this at file2 (where class A is):
class A:
def __init__(self):
import inspect
__f = inspect.getframeinfo(inspect.currentframe().f_back)
__func = __f.function
self.func_name = __func
__init__
, not in the class definition…!? – deceze ♦ Commented Feb 6 at 8:07__init__
rather than in the class definition, where the caller is the import system. – blhsing Commented Feb 6 at 8:18