Python Problems

From Official Kodi Wiki
Revision as of 13:26, 29 August 2022 by RogueScholar (talk | contribs) (Fix dead end page status with wikilinks and inline citations, and also −Category:Development; +Category:Python using HotCat)
Jump to navigation Jump to search
Home icon grey.png   ▶ Development ▶ Add-on development ▶ About Add-ons ▶ Python Problems


This page is meant to document Python issues of general interest to Kodi addon developers.

datetime.strptime

There is an old Python bug[1] which only impacts embedded Python applications, such as the Kodi Python environment. The issue is that datetime.strptime[2] 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).

Resolution options

One option is for you to replace every reference to datetime.strptime to use a patch, the code of which is shown below on this page. This involves less voodoo, but there is always the possibility that some library code uses strptime and that will cause the potential for incorrect results or a full Kodi crash, e.g. the YouTube-dl add-on (script.module.youtube.dl) was crashing Kodi for a while.

The other option 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.[3]; it discusses some of the differences between datetime.strptime and time.strptime.[4]

Patch

This patch simply replaces datetime.strptime with 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.[5] Essentially, the patch is:

    @staticmethod
    def monkey_patch_strptime():
        # Check if problem exists (don't want to stomp on patch applied earlier)
        try:
            datetime.datetime.strptime('0', '%H')
        except TypeError:
            # Globally replace Python's datetime.datetime.strptime with
            # the version here.
            datetime.datetime = StripTimePatch.strptime
    @staticmethod
    def strptime(date_string: str, date_format: str) -> datetime.datetime:
        result: datetime.datetime
        result = datetime.datetime(*(time.strptime(date_string, date_format)[0:6]))
        return result

References