Skip to content

Improve ctypes startup time #146547

@jonathandung

Description

@jonathandung

Feature or enhancement

Proposal:

In the ctypes source, sysconfig is loaded as early as line 5.

"""create and manipulate C data types in Python"""

import os as _os
import sys as _sys
import sysconfig as _sysconfig
import types as _types

However, scanning through the file, it is only used once, and in a conditional branch too:

if _os.name == "nt":
    pythonapi = PyDLL("python dll", None, _sys.dllhandle)
elif _sys.platform in ["android", "cygwin"]:
    # These are Unix-like platforms which use a dynamically-linked libpython.
    pythonapi = PyDLL(_sysconfig.get_config_var("LDLIBRARY"))
else:
    pythonapi = PyDLL(None)

The reason this is inefficient is that sysconfig imports threading instead of _thread, which cannot be helped since it has to use a top-level RLock. Correct me if I'm wrong, but this means at least 50 ms of import time.

I propose to move the import into this if branch. This may require a backport to 3.13 and 3.14, which have similar inefficiencies. (The import was not present prior.)

Has this already been discussed elsewhere?

This is a minor feature, which does not need previous discussion elsewhere

Links to previous discussion of this feature:

No response

Linked PRs

Metadata

Metadata

Assignees

No one assigned

    Labels

    pendingThe issue will be closed if no feedback is providedperformancePerformance or resource usagestdlibStandard Library Python modules in the Lib/ directorytopic-ctypestype-featureA feature request or enhancement

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions