Getting list functions in file that imported a module

霸气de小男生 提交于 2019-12-12 02:18:13

问题


This is for a project I am working on to help my own workflow, and nothing that is for production. So I understand that what I am doing is probably definitely not the right thing to do, but I am curious if it is possible anyways.

I have some code like this:

A.py:

from B import *

def f1():
    ...

def f2():
    ...

...

Is there any way for module B, when imported, to get a list of the functions defined in the importer, A.py?

I thought about using the inspect module, to inspect the call stack. But I was unsure where the entry point would be, I assume it would be in the global scope of B.py. I am also unsure what the call stack looks like when importing a module.

Any help would be appreciated.

Thanks!


回答1:


If you know what module you are going to import B.py in then you could have something like this:

A.py

import B

def f1():
    return 1

def f2():
    return 1

def f3():
    return 1

if __name__=="__main__":
    print temp.allF()

B.py

import inspect, A

def allF():
    return inspect.getmembers(A, inspect.isfunction)

When you run A.py it will give you a list of functions. I'm not sure if there is a way to access the script which imports a given module, but if this is possible then you could change B.py slightly to use this.



来源:https://stackoverflow.com/questions/43081310/getting-list-functions-in-file-that-imported-a-module

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!