|Development||Add-on development||About Add-ons||Python Problems|
This page is meant to document Python issues of general interest to Kodi addon developers.
There is an old Python bug which only impacts embedded Python applications, such as the Kodi Python environment. The issue is that
datetime.strptime is only initialized once per process, and not every time the embedded environment is reinitialized. This causes
datetime.strptime to return
None (and perhaps other strange behavior).
The workaround is to monkey-patch
datetime.strptime so that any user of the Python runtime will use it. It is more voodoo-like, but situations like this are why Python natively supports monkey patching, after all. The typically excellent Python documentation manages to be both thorough and concise simultaneously with regards to
datetime.strptime and is well worth reviewing before deciding which angle of attack best suits your use case.; it discusses some of the differences between
This patch simply replaces
time.strptime as they are nearly identical in function. The original Kodi-specific implementation and its commit history are available on GitHub as part of
script.module.kutils. Essentially, the patch is:
import datetime import time class proxydt(datetime.datetime): @classmethod def strptime(cls, date_string, format): return datetime.datetime(*(time.strptime(date_string, format)[:6])) datetime.datetime = proxydt
It is a known issue that
asyncio module or rather its C-based implementation does not support embedded Python environments that use sub-interpreters, such as Kodi Python environment. Essentially it means that only one addon can start the event loop by calling
asyncio.run() and others will fail with
The workaround is to disable C-based
asyncio module and use its pure-Python implementation. This can be done by the following code that should be put at the beginning of your addon entrypoint script:
import sys sys.modules['_asyncio'] = None
You will loose possible performance benefits of
asyncio but your async Python code won't fail.
- ↑ Weinberg, Denny (June 27, 2016). Issue #71587: Datetime NoneType after calling Py_Finalize and Py_Initialize. Python Issue Tracker on GitHub.
- ↑ Python 3 Documentation (August 28, 2022). The Python Standard Library » Data Types » datetime — Basic date and time types ― classmethod datetime.strptime(date_string, format) ― from the source code found in Lib/datetime.py.
- ↑ Python 3 Documentation (August 28, 2022). datetime — Basic date and time types » strftime() and strptime() Behavior.
- ↑ Python 3 Documentation (August 28, 2022). strftime() and strptime() Behavior » Technical Detail.
- ↑ lib/kutils/strptime_patch.py (January 11, 2022) in
script.module.kutils, "A helper module for Kodi development" on GitHub.