如何为 datetime 等 stdlib 模块启用纯 Python 模块而不是 C 加速版本
How to enable a pure Python module instead of a C accelerated version for a stdlib module such as datetime
一些 stdlib 模块(例如 datetime
、decimal
、io
)同时具有 C 和纯 Python 实现,例如,参见 PEP 399 -- Pure Python/C Accelerator Module Compatibility Requirements。
可能需要禁用 C 加速版本。
对于decimal
、io
模块我可以直接导入_pydecimal
和_pyio
模块。如何访问纯 Python datetime
实现?
C 加速版本 (_datetime
) 在 datetime.py
中使用 from _datetime import *
启用,因此足以导致 ImportError 并重新加载 datetime 模块,以防它已被导入早些时候:
import importlib
import sys
sys.modules['_datetime'] = None # cause ImportError
datetime = importlib.reload(importlib.import_module('datetime'))
测试:
>>> datetime.timedelta(1<<30)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/python3.4/datetime.py", line 430, in __new__
raise OverflowError("timedelta # of days is too large: %d" % d)
OverflowError: timedelta # of days is too large: 1073741824
回溯显示使用的是纯 Python 版本。
一些 stdlib 模块(例如 datetime
、decimal
、io
)同时具有 C 和纯 Python 实现,例如,参见 PEP 399 -- Pure Python/C Accelerator Module Compatibility Requirements。
可能需要禁用 C 加速版本。
对于decimal
、io
模块我可以直接导入_pydecimal
和_pyio
模块。如何访问纯 Python datetime
实现?
C 加速版本 (_datetime
) 在 datetime.py
中使用 from _datetime import *
启用,因此足以导致 ImportError 并重新加载 datetime 模块,以防它已被导入早些时候:
import importlib
import sys
sys.modules['_datetime'] = None # cause ImportError
datetime = importlib.reload(importlib.import_module('datetime'))
测试:
>>> datetime.timedelta(1<<30)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/python3.4/datetime.py", line 430, in __new__
raise OverflowError("timedelta # of days is too large: %d" % d)
OverflowError: timedelta # of days is too large: 1073741824
回溯显示使用的是纯 Python 版本。