如何区分python中的导入和函数定义?

问题描述 投票:1回答:1

我正在写一个python函数,它可以在一个文件列表中搜索带有特定装饰符的文件。我把模块抓过来。

# Load modules from files
loader = machinery.SourceFileLoader(file_name, file_path)
spec = util.spec_from_loader(loader.name, loader)
module = util.module_from_spec(spec)
loader.exec_module(module)

# fetch functions
functions = [function for function in dir(module)]

但我有以下问题

file1.py

@dork
def does_something():
   pass

file2.py

from file1 import does_something

所以当我搜索装饰符时,我得到两个路径:'file1.does_something''file2.does_something'。

当我只想要file1的路径时。有没有办法区分实际函数和导入?

python python-3.x
1个回答
0
投票

"如何区分python中的导入和函数定义?" 在你分析这个问题的层面上,这并不是一个区别。该 同功能对象 的名字空间中,存在两个 不同模块对象. 这是一个需要分析的区别。源码,而不是模块对象。

不过这里有一个潜在的黑客,检查是否。

func.__module__ == module.__name__
© www.soinside.com 2019 - 2024. All rights reserved.