如何找到哪个函数来自“from - import”模块

问题描述

我对“from - import”功能有疑问。例如。我有 3 个文件:one.py、two.py、three.py。

three.py文件内容

from one import *
from two import *


variable1
variable2

def func1()

def func2()

def func3()

比方说,我没有以上两个文件的权限,我无法打开它们。我的问题是,如何检查哪个函数和哪个变量来自 one.py 或 two.py 文件?有什么命令之类的吗?

解决方法

您可以使用 getfile 模块中的 inspect

Return the name of the (text or binary) file in which an object was defined. This will fail with a TypeError if the object is a built-in module,class,or function.

https://docs.python.org/3/library/inspect.html#inspect.getfile

,
print(func1.__module__)
print(func2.__module__)
print(func3.__module__)
,

您可以将 try-except 应用于导入语句。

try:
  from one import *
  from two import *
except ImportError:
  # Override variables after failed import
  var1 = ...
  var2 = ...
,

可以使用模块的命名空间调用函数\变量

并使用 try/ 进行检查,但在导入模块时不会出现错误

   try:
       from one
       one.foo()
       one.variable1

   except ImportError as exception:
       print(exception)

   try:
       from two
       two.foo()
       two.variable1

   except ImportError as exception:
       print(exception)