Create a Python type from C that implements a __dict__?

前端 未结 4 2275
日久生厌
日久生厌 2021-02-15 16:22
  • How is a type created to have a __dict__ as per a \"normal\" class would have were it defined in Python?
  • Are there any examples of non-dynamic types
4条回答
  •  醉话见心
    2021-02-15 16:59

    To answer the last question first: No, type_new is only used for "heap types" that are dynamically defined at runtime (e.g. via a class statement). Statically defined types are initialised using PyType_Ready() instead.

    To answer your first question: to create an extension type with a __dict__ descriptor, you need to dynamically allocate the type the same way the interpreter does for a class definition.

    One way to get examples for that is to do as John suggests and generate some examples of your own with Cython.

    For CPython 2.x you can look at the build_class method in the CPython source code (http://svn.python.org/view/python/trunk/Python/ceval.c?view=markup) to get an idea of the steps involved in a fully general solution.

    If you're using Python 3 though, then this question may be of interest: What does Python's builtin __build_class__ do?

    That is, as a CPython 3.x specific solution, the simplest thing to do is call builtins.__build_class__ with appropriate arguments via the C API.

提交回复
热议问题