Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

GH-118761: Expose more core interpreter types in _types #132103

Merged
merged 10 commits into from
Apr 5, 2025
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
118 changes: 61 additions & 57 deletions Lib/types.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,67 +2,78 @@
Define names for built-in types that aren't directly accessible as a builtin.
"""

import _types

# Iterators in Python aren't a matter of type but of protocol. A large
# and changing number of builtin types implement *some* flavor of
# iterator. Don't check the type! Use hasattr to check for both
# "__iter__" and "__next__" attributes instead.

def _f(): pass
FunctionType = type(_f)
LambdaType = type(lambda: None) # Same as FunctionType
CodeType = type(_f.__code__)
MappingProxyType = type(type.__dict__)
SimpleNamespace = _types.SimpleNamespace

def _cell_factory():
a = 1
def f():
nonlocal a
return f.__closure__[0]
CellType = type(_cell_factory())

def _g():
yield 1
GeneratorType = type(_g())

async def _c(): pass
_c = _c()
CoroutineType = type(_c)
_c.close() # Prevent ResourceWarning

async def _ag():
yield
_ag = _ag()
AsyncGeneratorType = type(_ag)

class _C:
def _m(self): pass
MethodType = type(_C()._m)

BuiltinFunctionType = type(len)
BuiltinMethodType = type([].append) # Same as BuiltinFunctionType
try:
from _types import *
except ImportError:
import sys

def _f(): pass
FunctionType = type(_f)
LambdaType = type(lambda: None) # Same as FunctionType
CodeType = type(_f.__code__)
MappingProxyType = type(type.__dict__)
SimpleNamespace = type(sys.implementation)

def _cell_factory():
a = 1
def f():
nonlocal a
return f.__closure__[0]
CellType = type(_cell_factory())

def _g():
yield 1
GeneratorType = type(_g())

async def _c(): pass
_c = _c()
CoroutineType = type(_c)
_c.close() # Prevent ResourceWarning

async def _ag():
yield
_ag = _ag()
AsyncGeneratorType = type(_ag)

class _C:
def _m(self): pass
MethodType = type(_C()._m)

BuiltinFunctionType = type(len)
BuiltinMethodType = type([].append) # Same as BuiltinFunctionType

WrapperDescriptorType = type(object.__init__)
MethodWrapperType = type(object().__str__)
MethodDescriptorType = type(str.join)
ClassMethodDescriptorType = type(dict.__dict__['fromkeys'])

ModuleType = type(sys)

WrapperDescriptorType = type(object.__init__)
MethodWrapperType = type(object().__str__)
MethodDescriptorType = type(str.join)
ClassMethodDescriptorType = type(dict.__dict__['fromkeys'])
try:
raise TypeError
except TypeError as exc:
TracebackType = type(exc.__traceback__)
FrameType = type(exc.__traceback__.tb_frame)

ModuleType = type(_types)
GetSetDescriptorType = type(FunctionType.__code__)
MemberDescriptorType = type(FunctionType.__globals__)

try:
raise TypeError
except TypeError as exc:
TracebackType = type(exc.__traceback__)
FrameType = type(exc.__traceback__.tb_frame)
GenericAlias = type(list[int])
UnionType = type(int | str)

GetSetDescriptorType = type(FunctionType.__code__)
MemberDescriptorType = type(FunctionType.__globals__)
EllipsisType = type(Ellipsis)
NoneType = type(None)
NotImplementedType = type(NotImplemented)

CapsuleType = _types.CapsuleType
# CapsuleType cannot be accessed from pure Python,
# so there is no fallback definition.

del _types, _f, _g, _C, _c, _ag, _cell_factory # Not for export
del sys, _f, _g, _C, _c, _ag, _cell_factory # Not for export


# Provide a PEP 3115 compliant mechanism for class creation
Expand Down Expand Up @@ -326,11 +337,4 @@ def wrapped(*args, **kwargs):

return wrapped

GenericAlias = type(list[int])
UnionType = type(int | str)

EllipsisType = type(Ellipsis)
NoneType = type(None)
NotImplementedType = type(NotImplemented)

__all__ = [n for n in globals() if not n.startswith('_')] # for pydoc
80 changes: 80 additions & 0 deletions Modules/_typesmodule.c
Original file line number Diff line number Diff line change
@@ -1,17 +1,97 @@
/* _types module */

#include "Python.h"
#include "pycore_descrobject.h" // _PyMethodWrapper_Type
#include "pycore_namespace.h" // _PyNamespace_Type
#include "pycore_object.h" // _PyNone_Type, _PyNotImplemented_Type
#include "pycore_unionobject.h" // _PyUnion_Type

static int
_types_exec(PyObject *m)
{
if (PyModule_AddObjectRef(m, "AsyncGeneratorType", (PyObject *)&PyAsyncGen_Type) < 0) {
return -1;
}
if (PyModule_AddObjectRef(m, "BuiltinFunctionType", (PyObject *)&PyCFunction_Type) < 0) {
return -1;
}
// Same as BuiltinMethodType
if (PyModule_AddObjectRef(m, "BuiltinMethodType", (PyObject *)&PyCFunction_Type) < 0) {
return -1;
}
if (PyModule_AddObjectRef(m, "CapsuleType", (PyObject *)&PyCapsule_Type) < 0) {
return -1;
}
if (PyModule_AddObjectRef(m, "CellType", (PyObject *)&PyCell_Type) < 0) {
return -1;
}
if (PyModule_AddObjectRef(m, "ClassMethodDescriptorType", (PyObject *)&PyClassMethodDescr_Type) < 0) {
return -1;
}
if (PyModule_AddObjectRef(m, "CodeType", (PyObject *)&PyCode_Type) < 0) {
return -1;
}
if (PyModule_AddObjectRef(m, "CoroutineType", (PyObject *)&PyCoro_Type) < 0) {
return -1;
}
if (PyModule_AddObjectRef(m, "EllipsisType", (PyObject *)&PyEllipsis_Type) < 0) {
return -1;
}
if (PyModule_AddObjectRef(m, "FrameType", (PyObject *)&PyFrame_Type) < 0) {
return -1;
}
if (PyModule_AddObjectRef(m, "FunctionType", (PyObject *)&PyFunction_Type) < 0) {
return -1;
}
if (PyModule_AddObjectRef(m, "GeneratorType", (PyObject *)&PyGen_Type) < 0) {
return -1;
}
if (PyModule_AddObjectRef(m, "GenericAlias", (PyObject *)&Py_GenericAliasType) < 0) {
return -1;
}
if (PyModule_AddObjectRef(m, "GetSetDescriptorType", (PyObject *)&PyGetSetDescr_Type) < 0) {
return -1;
}
// Same as FunctionType
if (PyModule_AddObjectRef(m, "LambdaType", (PyObject *)&PyFunction_Type) < 0) {
return -1;
}
if (PyModule_AddObjectRef(m, "MappingProxyType", (PyObject *)&PyDictProxy_Type) < 0) {
return -1;
}
if (PyModule_AddObjectRef(m, "MemberDescriptorType", (PyObject *)&PyMemberDescr_Type) < 0) {
return -1;
}
if (PyModule_AddObjectRef(m, "MethodDescriptorType", (PyObject *)&PyMethodDescr_Type) < 0) {
return -1;
}
if (PyModule_AddObjectRef(m, "MethodType", (PyObject *)&PyMethod_Type) < 0) {
return -1;
}
if (PyModule_AddObjectRef(m, "MethodWrapperType", (PyObject *)&_PyMethodWrapper_Type) < 0) {
return -1;
}
if (PyModule_AddObjectRef(m, "ModuleType", (PyObject *)&PyModule_Type) < 0) {
return -1;
}
if (PyModule_AddObjectRef(m, "NoneType", (PyObject *)&_PyNone_Type) < 0) {
return -1;
}
if (PyModule_AddObjectRef(m, "NotImplementedType", (PyObject *)&_PyNotImplemented_Type) < 0) {
return -1;
}
if (PyModule_AddObjectRef(m, "SimpleNamespace", (PyObject *)&_PyNamespace_Type) < 0) {
return -1;
}
if (PyModule_AddObjectRef(m, "TracebackType", (PyObject *)&PyTraceBack_Type) < 0) {
return -1;
}
if (PyModule_AddObjectRef(m, "UnionType", (PyObject *)&_PyUnion_Type) < 0) {
return -1;
}
if (PyModule_AddObjectRef(m, "WrapperDescriptorType", (PyObject *)&PyWrapperDescr_Type) < 0) {
return -1;
}
return 0;
}

Expand Down
Loading