1

My module what know who call its function, like

a.py

importlib.import_module("b")
b.b()

b.py

def b():
    importlib.import_module("c")
    print(parent_module)
    c.c()

c.py

import c

def c():
    print(parent_module)

I want b() print module a, and c() print b

I tried this func

def get_parent_name():
    print('get parent module')
    print(os.path.splitext(os.path.basename(getframeinfo(stack()[-1][0]).filename))[0])

but it can only get the toppest module, like

b() print a and c() print a

InSync
  • 4,851
  • 4
  • 8
  • 30
Tnxts
  • 21
  • 3
  • This qustion might solve my problem [how-to-use-inspect-to-get-the-callers-info-from-callee-in-python](https://stackoverflow.com/questions/3711184/how-to-use-inspect-to-get-the-callers-info-from-callee-in-python) – Tnxts Jun 04 '23 at 02:05

1 Answers1

0

It's another answer Get __name__ of calling function's module in Python, I dont recommand to use inspect.stack[2] because when i use it to get the caller's module name that i can get "inspect" only, so it wrong.
I recommand to use enter image description here this method.You can get the caller module by this func

def caller_module():
    frame = inspect.currentframe()
    frame = frame.f_back.f_back
    return inspect.getmodule(frame)

Tnxts
  • 21
  • 3