Skip to content

Cython mishandles PEP-3135 __class__ cell in methods #2912

@marginalhours

Description

@marginalhours

Hello, I am having trouble with some inconsistent behaviour round the value of __class__ in Cythonized code. This is on Python 3.6.7 with Cython 0.29.1.

Briefly, in uncythonized code __class__ inside a method on a class refers to the class object, whereas once cythonized, it seems to refer to <class 'module'>. This behaviour is a bit unintuitive, and has caused a few issues in a codebase I'm working on, but it's possible I have misunderstood the language semantics!

I have tried to search for reasons / documentation why this is the case, but I couldn't turn up anything. I apologise if there is something really obvious I'm missing here; let me know if so and I'll close the issue at once.

Example:

minimal.py:

class Something:
    def method(self):
        print(__class__)

(in an interpreter, uncythonized):

from minimal import Something
Something().method()
# prints <class 'minimal.Something'>

(after running cythonize minimal.py -3):

from minimal import Something
Something().method()
# prints <class 'module'>   

I believe there is an obvious workaround -- in instance methods, self.__class__ should still have the correct value. But I was curious if this is intended behaviour, and if so, is there something in the docs about it?

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions