Skip to content

Use PyObject_GetTypeData without the GIL/attached thread state #142376

@da-woods

Description

@da-woods

Feature or enhancement

Proposal:

In Cython we've historically let people do things like:

cdef class C:
    cdef int non_object_attribute

def f(C c):
    with nogil:
        value = c.non_object_attribute
        ...

i.e. we've allowed them to get direct access into extension types without the GIL (providing they aren't manipulating Python objects).

When using PEP 697 lookup this becomes a little trickier because access to the attribute has to go through PyObject_GetTypeData. Looking at the implementation of PyObject_GetTypeData, it doesn't appear to need the GIL (except in debug mode where it sanity-checks the type).

I think I can work around this by calculating the offset of the struct myself once at startup (using PyObject_GetTypeData) and then doing all the lookups manually via the offset. It also looks like nanobind use a similar trick in places so I wouldn't be alone in this abuse of the system.

However, it'd be nice not to have to do this and if PyObject_GetTypeData could somehow be exempted from the "C API needs the GIL" rule.

I do understand that people would probably prefer not to do this, so I'm happy to look at other options.

Has this already been discussed elsewhere?

I have already discussed this feature proposal on Discourse

Links to previous discussion of this feature:

I asked about this in https://discuss.python.org/t/does-pyobject-gettypedata-need-the-gil/104637/4 - it only generated a small amount of discussion.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions