Python 炫技操作:模塊重載的五種方法


環境准備

新建一個 foo 文件夾,其下包含一個 bar.py 文件

$ tree foo
foo
└── bar.py

0 directories, 1 file

bar.py 的內容非常簡單,只寫了個 print 語句

print("successful to be imported")

只要 bar.py 被導入一次,就被執行一次 print

禁止重復導入

'由於有 sys.modules 的存在,當你導入一個已導入的模塊時,實際上是沒有效果的。'

>>> from foo import bar
successful to be imported
>>> from foo import bar
>>>

重復導入方法一

如果你使用的 python2(記得前面在 foo 文件夾下加一個 __init__.py),有一個 reload 的方法可以直接使用

>>> from foo import bar
successful to be imported
>>> from foo import bar
>>>
>>> reload(bar)
successful to be imported
<module 'foo.bar' from 'foo/bar.pyc'>

如果你使用的 python3 那方法就多了,詳細請看下面

重復導入方法二

如果你使用 Python3.0 -> 3.3,那么可以使用 imp.reload 方法

>>> from foo import bar
successful to be imported
>>> from foo import bar
>>>
>>> import imp
>>> imp.reload(bar)
successful to be imported
<module 'foo.bar' from '/Users/MING/Code/Python/foo/bar.py'>

但是這個方法在 Python 3.4+,就不推薦使用了

<stdin>:1: DeprecationWarning: the imp module is deprecated in favour of importlib; see the module's documentation for alternative uses

重復導入方法三

如果你使用的 Python 3.4+,請使用 importlib.reload 方法

>>> from foo import bar
successful to be imported
>>> from foo import bar
>>>
>>> import importlib
>>> importlib.reload(bar)
successful to be imported
<module 'foo.bar' from '/Users/MING/Code/Python/foo/bar.py'>

重復導入方法四

如果你對包的加載器有所了解(詳細可以翻閱我以前寫的文章:https://iswbm.com/84.html)

還可以使用下面的方法

>>> from foo import bar
successful to be imported
>>> from foo import bar
>>>
>>> bar.__spec__.loader.load_module()
successful to be imported
<module 'foo.bar' from '/Users/MING/Code/Python/foo/bar.py'>

重復導入方法五

既然影響我們重復導入的是 sys.modules,那我們只要將已導入的包從其中移除是不是就好了呢?

>>> import foo.bar
successful to be imported
>>>
>>> import foo.bar
>>>
>>> import sys
>>> sys.modules['foo.bar']
<module 'foo.bar' from '/Users/MING/Code/Python/foo/bar.py'>
>>> del sys.modules['foo.bar']
>>>
>>> import foo.bar
successful to be imported

有沒有發現在前面的例子里我使用的都是 from foo import bar,在這個例子里,卻使用 import foo.bar,這是為什么呢?

這是因為如果你使用 from foo import bar 這種方式,想使用移除 sys.modules 來重載模塊這種方法是失效的。

這應該算是一個小坑,不知道的人,會掉入坑中爬不出來。

>>> import foo.bar
successful to be imported
>>>
>>> import foo.bar
>>>
>>> import sys
>>> del sys.modules['foo.bar']
>>> from foo import bar
>>>

推薦下我本人原創的 《PyCharm 中文指南》電子書,內含大量(300張)的圖解制作之精良,值得每個 Python 工程師點個收藏。

地址是:http://pycharm.iswbm.com


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM