测试环境准备:
1、在site-packages下新建一个用于测试的包,包含如下文件
2、文件的内容:
a.py
# -*- coding:utf-8 -*-
from __future__ import print_function, unicode_literals, division
from future_builtins import *
print('initializing a')
if '__main__' == __name__:
pass
from __future__ import print_function, unicode_literals, division
from future_builtins import *
print('initializing a')
if '__main__' == __name__:
pass
b.py
# -*- coding:utf-8 -*-
from __future__ import print_function, unicode_literals, division
from future_builtins import *
from import_test import a
import a, c
if '__main__' == __name__:
pass
from __future__ import print_function, unicode_literals, division
from future_builtins import *
from import_test import a
import a, c
if '__main__' == __name__:
pass
c.py
# -*- coding:utf-8 -*-
from __future__ import print_function, unicode_literals, division
from future_builtins import *
from import_test import a
import a
if '__main__' == __name__:
pass
from __future__ import print_function, unicode_literals, division
from future_builtins import *
from import_test import a
import a
if '__main__' == __name__:
pass
在命令行上执行python b.py,出现如下结果:
为什么会这样?从过程来看,就是from...import和import找到的module被python认为是两个玩意,所以初始化了两次(代码中from...import和import分别执行了两次,a一共被import四次,只是被同样语句import进来的module被缓存了,所以只初始化了两次)。
项目中遇到这种情况一定要小心,重复初始化module浪费内存只是小事,要是module的逻辑过于复杂而导致什么莫名其妙的bug那才叫杯具。