J.F. Sebastian J.F. Sebastian - 1 month ago 10
Python Question

How to enable a pure Python module instead of a C accelerated version for a stdlib module such as datetime

Some stdlib modules (such as

datetime
,
decimal
,
io
) have both C and pure Python implementations e.g., see PEP 399 -- Pure Python/C Accelerator Module Compatibility Requirements.

It might be desirable to disable the C accelerated version.

For
decimal
,
io
modules I can import
_pydecimal
and
_pyio
modules directly. How to get access to the pure Python
datetime
implementation?

Answer

The C accelarated version (_datetime) is enabled in datetime.py using from _datetime import * and therefore it is enough to cause ImportError and reload the datetime module in case it has been already imported earlier:

import importlib
import sys

sys.modules['_datetime'] = None # cause ImportError
datetime = importlib.reload(importlib.import_module('datetime')) 

Test:

>>> 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

The traceback shows that the pure Python version is used.