Why is PyDateTimeAPI not initialized by datetime module import?
I just got burned (wasted a good day or so) by the fact that PyDateTimeAPI wasn't initialized. The datetime.rst doc states (emphasis mine): Before using any of these functions, the header file :file:`datetime.h` must be included in your source (note that this is not included by :file:`Python.h`), and the macro :c:macro:`PyDateTime_IMPORT` must be invoked, *usually as part of the module initialisation function*. I thought that surely the datetime module itself would initialize that stuff. Why not? Is it so terribly expensive that the C API requires this rather weird hack? The code's been their for ages, so there must have been a good reason at one time. Is that reason still valid today? (I haven't programmed at the C API level for a good long while, or I'm sure I'd have encountered this before.) Thx, Skip
On Thu, Jan 26, 2017 at 11:00 AM, Skip Montanaro
I just got burned (wasted a good day or so) by the fact that PyDateTimeAPI wasn't initialized. The datetime.rst doc states (emphasis mine):
Before using any of these functions, the header file :file:`datetime.h` must be included in your source (note that this is not included by :file:`Python.h`), and the macro :c:macro:`PyDateTime_IMPORT` must be invoked, *usually as part of the module initialisation function*.
I thought that surely the datetime module itself would initialize that stuff. Why not?
It is fairly common for the modules that export C API in a capsule to only initialize that capsule when explicitly asked. For example, if you want to use numpy C API, you need to call import_array() in your module initialization function. [1] I don't know how expensive PyDateTime_IMPORT is, but it cannot be called in _datetimemodule.c because it is guarded by the Py_BUILD_CORE macro and is not available when _datetimemodule.c itself is compiled. I don't know whether this can be easily circumvented, but it is not hard to remember that one should initialize C API before using it. Maybe we can improve the error message when PyDateTime_IMPORT is forgotten. Feel free to open an issue for that. [1]: https://docs.scipy.org/doc/numpy-1.12.0/user/c-info.how-to-extend.html#requi...
participants (2)
-
Alexander Belopolsky
-
Skip Montanaro