Skip to content

Add _types module#6807

Merged
youknowone merged 5 commits intoRustPython:mainfrom
youknowone:_types
Feb 8, 2026
Merged

Add _types module#6807
youknowone merged 5 commits intoRustPython:mainfrom
youknowone:_types

Conversation

@youknowone
Copy link
Member

@youknowone youknowone commented Jan 20, 2026

the _ prefixed name is related to #3284

Summary by CodeRabbit

Release Notes

  • New Features

    • Added Capsule type for Python capsule objects.
    • Introduced _types module providing access to built-in type objects including AsyncGeneratorType, BuiltinFunctionType, BuiltinMethodType, CapsuleType, CodeType, FunctionType, GeneratorType, MethodType, ModuleType, and others.
  • Refactor

    • Unified native function and bound method types under a consolidated representation.

✏️ Tip: You can customize this high-level summary in your review settings.

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Jan 20, 2026

Important

Review skipped

Review was skipped due to path filters

⛔ Files ignored due to path filters (1)
  • Lib/test/test_reprlib.py is excluded by !Lib/**

CodeRabbit blocks several paths by default. You can override this behavior by explicitly including those paths in the path filters. For example, including **/dist/** will override the default block on the dist directory, by removing the pattern from both the lists.

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

  • 🔍 Trigger a full review
📝 Walkthrough

Walkthrough

The changes refactor the builtin function and method type hierarchy to unify PyNativeFunction and PyNativeMethod under a shared "builtin_function_or_method" type with C-compatible representation, introduce a new PyCapsule type for capsule objects, and add a centralized _types module exposing all built-in Python type objects as accessor functions.

Changes

Cohort / File(s) Summary
Native Function & Method Type Unification
crates/vm/src/builtins/builtin_func.rs, crates/vm/src/function/method.rs
PyNativeFunction now includes #[repr(C)] annotation and expanded fields (value, zelf, module). PyNativeMethod inherits from PyNativeFunction and shares the builtin_function_or_method type. Introduces NativeFunctionOrMethod wrapper for common data access. Method building updated to use the unified type instead of distinct builtin_method_type.
Capsule Type Implementation
crates/vm/src/builtins/capsule.rs, crates/vm/src/builtins/mod.rs
New PyCapsule struct added with Representable and PyPayload trait implementations, producing <capsule object> repr. Module declaration and re-export added to builtins.
Built-in Type Exposure
crates/vm/src/stdlib/_types.rs, crates/vm/src/stdlib/mod.rs
New _types module created with 23+ accessor functions (AsyncGeneratorType, BuiltinFunctionType, CapsuleType, etc.) returning Python type objects from vm.ctx.types. Module integrated into builtin_module_defs initialization.
Type Registry Updates
crates/vm/src/types/zoo.rs
TypeZoo struct gains new capsule_type field. Capsule type initialized via PyCapsule::init_builtin_type(). builtin_function_or_method_type now reuses same type instance as builtin_method_type. Capsule initialization invoked in extension flow.

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Possibly related PRs

Suggested reviewers

  • arihant2math
  • coolreader18

Poem

A rabbit hops through builtin lands,
Native functions now join paws and hands,
Capsules bundled, types on display,
_types module lights the way,
One grand type zoo, hip hooray! 🐰✨

🚥 Pre-merge checks | ✅ 3
✅ Passed checks (3 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title 'Add _types module' accurately summarizes the main change: introducing a new _types module with type accessors, though it omits supporting infrastructure changes like PyCapsule and builtin_function_or_method consolidation.
Docstring Coverage ✅ Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@youknowone youknowone changed the title _types Add _types module Jan 24, 2026
@youknowone youknowone marked this pull request as ready for review January 24, 2026 13:08
Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🤖 Fix all issues with AI agents
In `@crates/vm/src/stdlib/_types.rs`:
- Around line 107-111: The ClassMethodDescriptorType function currently returns
vm.ctx.types.method_descriptor_type, causing types.ClassMethodDescriptorType to
be identical to MethodDescriptorType; instead either register and return a
distinct type object for class method descriptors (e.g. create and expose a new
vm.ctx.types.class_method_descriptor_type via the same type-registration flow
used for other descriptor types and return that from ClassMethodDescriptorType)
or remove/withhold the pyattr until the dedicated type is implemented; update
the ClassMethodDescriptorType implementation to return the new unique type
symbol (class_method_descriptor_type) rather than method_descriptor_type so type
identity matches CPython.
🧹 Nitpick comments (2)
crates/vm/src/builtins/capsule.rs (1)

10-16: Consider simplifying the struct definition.

Since PyCapsule only contains a unit field _private: (), the Clone and Copy derives are technically fine but may be unnecessary. If capsule functionality expands in the future to hold actual data (e.g., raw pointers for FFI), these derives would need reconsideration.

♻️ Optional simplification
-#[derive(Debug, Clone, Copy)]
+#[derive(Debug)]
 pub struct PyCapsule {
     _private: (),
 }
crates/vm/src/builtins/builtin_func.rs (1)

233-244: Consider adding a SAFETY comment to the unsafe block.

The downcast_unchecked relies on the #[repr(C)] layout invariant established in the struct definitions. Adding an explicit // SAFETY: comment would help future maintainers understand why this cast is valid.

📝 Suggested documentation
         if obj.fast_isinstance(class) {
-            // Both PyNativeFunction and PyNativeMethod share the same type now.
-            // PyNativeMethod has `func: PyNativeFunction` as its first field,
-            // so we can safely treat the data pointer as PyNativeFunction for reading.
+            // SAFETY: Both PyNativeFunction and PyNativeMethod share the same Python type.
+            // PyNativeMethod has `func: PyNativeFunction` as its first field with #[repr(C)],
+            // guaranteeing func is at offset 0. This allows safely reading PyNativeFunction
+            // fields from either type.
             Ok(Self(unsafe { obj.downcast_unchecked() }))

Comment on lines +107 to +111
#[pyattr]
fn ClassMethodDescriptorType(vm: &VirtualMachine) -> PyObjectRef {
// TODO: implement as separate type
vm.ctx.types.method_descriptor_type.to_owned().into()
}
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major

ClassMethodDescriptorType should not alias MethodDescriptorType.

On Line 109, this TODO means types.ClassMethodDescriptorType becomes identical to types.MethodDescriptorType, which diverges from CPython and can break code that relies on type identity checks. Please introduce a dedicated type (or avoid exposing this attribute until it exists).

🤖 Prompt for AI Agents
In `@crates/vm/src/stdlib/_types.rs` around lines 107 - 111, The
ClassMethodDescriptorType function currently returns
vm.ctx.types.method_descriptor_type, causing types.ClassMethodDescriptorType to
be identical to MethodDescriptorType; instead either register and return a
distinct type object for class method descriptors (e.g. create and expose a new
vm.ctx.types.class_method_descriptor_type via the same type-registration flow
used for other descriptor types and return that from ClassMethodDescriptorType)
or remove/withhold the pyattr until the dedicated type is implemented; update
the ClassMethodDescriptorType implementation to return the new unique type
symbol (class_method_descriptor_type) rather than method_descriptor_type so type
identity matches CPython.

@github-actions
Copy link
Contributor

Code has been automatically formatted

The code in this PR has been formatted using:

  • cargo fmt --all
    Please pull the latest changes before pushing again:
git pull origin _types

@github-actions
Copy link
Contributor

github-actions bot commented Feb 8, 2026

📦 Library Dependencies

The following Lib/ modules were modified. Here are their dependencies:

[x] lib: cpython/Lib/reprlib.py
[x] test: cpython/Lib/test/test_reprlib.py (TODO: 3)

dependencies:

  • reprlib

dependent tests: (162 tests)

  • reprlib: test_reprlib
    • collections: test_annotationlib test_array test_asyncio test_bisect test_builtin test_c_locale_coercion test_call test_collections test_configparser test_contains test_csv test_ctypes test_defaultdict test_deque test_dict test_dictviews test_enum test_exception_group test_file test_fileinput test_fileio test_functools test_genericalias test_hash test_httpservers test_inspect test_io test_ipaddress test_iter test_iterlen test_json test_ordered_dict test_pathlib test_patma test_pickle test_plistlib test_pprint test_random test_set test_shelve test_sqlite3 test_statistics test_string test_struct test_traceback test_types test_typing test_unittest test_urllib test_userdict test_userlist test_userstring test_weakref test_weakset test_with
      • concurrent.futures._base: test_concurrent_futures
      • configparser: test_logging
      • dbm.dumb: test_dbm_dumb
      • dbm.sqlite3: test_dbm_sqlite3
      • difflib: test_difflib test_sys_settrace
      • dis: test__opcode test_ast test_code test_compile test_compiler_assemble test_dis test_dtrace test_fstring test_opcache test_peepholer test_positional_only_arg
      • http.client: test_docxmlrpc test_hashlib test_ssl test_ucn test_unicodedata test_urllib2 test_wsgiref test_xmlrpc
      • importlib.metadata: test_importlib test_zoneinfo
      • inspect: test_abc test_argparse test_asyncgen test_coroutines test_decimal test_generators test_grammar test_ntpath test_operator test_posixpath test_signal test_yield_from test_zipimport
      • multiprocessing: test_asyncio test_concurrent_futures test_fcntl test_multiprocessing_main_handling
      • pkgutil: test_pkgutil
      • platform: test__locale test__osx_support test_android test_asyncio test_baseexception test_cmath test_ctypes test_math test_mimetypes test_os test_platform test_posix test_regrtest test_socket test_sysconfig test_time test_winreg
      • pprint: test_htmlparser test_sys_setprofile
      • queue: test_asyncio test_concurrent_futures test_dummy_thread test_sched
      • selectors: test_selectors test_subprocess
      • shutil: test_bz2 test_compileall test_ctypes test_filecmp test_glob test_importlib test_largefile test_py_compile test_shutil test_site test_string_literals test_support test_tempfile test_venv
      • tokenize: test_linecache test_tabnanny test_tokenize test_unparse
      • traceback: test_asyncio test_code_module test_contextlib test_contextlib_async test_importlib test_listcomps test_pyexpat test_setcomps test_threadedtempfile test_threading test_unittest
      • urllib.parse: test_sqlite3 test_urllib2_localnet test_urllibnet test_urlparse
      • urllib.robotparser: test_robotparser
      • wave: test_wave
    • dataclasses: test__colorize

[x] lib: cpython/Lib/threading.py
[x] lib: cpython/Lib/_threading_local.py
[ ] test: cpython/Lib/test/test_threading.py (TODO: 19)
[ ] test: cpython/Lib/test/test_threadedtempfile.py
[ ] test: cpython/Lib/test/test_threading_local.py (TODO: 3)

dependencies:

  • threading

dependent tests: (109 tests)

  • threading: test_android test_asyncio test_bz2 test_code test_concurrent_futures test_contextlib test_ctypes test_decimal test_docxmlrpc test_email test_enum test_fork1 test_ftplib test_functools test_hashlib test_httplib test_httpservers test_imaplib test_importlib test_io test_itertools test_largefile test_logging test_opcache test_poll test_queue test_robotparser test_sched test_signal test_smtplib test_socket test_socketserver test_sqlite3 test_ssl test_subprocess test_super test_syslog test_termios test_threadedtempfile test_threading test_threading_local test_time test_urllib2_localnet test_weakref test_winreg test_wsgiref test_xmlrpc test_zstd
    • asyncio: test_asyncio test_contextlib_async test_inspect test_os test_sys_settrace test_unittest
    • concurrent.futures._base: test_concurrent_futures
    • concurrent.futures.process: test_concurrent_futures
    • concurrent.futures.thread: test_genericalias
    • http.cookiejar: test_http_cookiejar
    • logging: test_support test_unittest
      • venv: test_venv
    • multiprocessing: test_fcntl test_multiprocessing_main_handling
    • queue: test_dummy_thread
    • subprocess: test_audit test_c_locale_coercion test_cmd_line test_cmd_line_script test_ctypes test_dtrace test_faulthandler test_file_eintr test_gzip test_json test_msvcrt test_ntpath test_osx_env test_platform test_plistlib test_py_compile test_regrtest test_repl test_runpy test_script_helper test_select test_shutil test_site test_sys test_sysconfig test_tempfile test_unittest test_urllib2 test_utf8_mode test_wait3 test_webbrowser test_zipfile
      • ctypes.util: test_ctypes
      • ensurepip: test_ensurepip
    • sysconfig: test_pyexpat test_tools test_urllib2net
      • trace: test_trace
    • zipfile: test_pkgutil test_zipapp test_zipfile test_zipfile64 test_zipimport
      • importlib.metadata: test_importlib test_zoneinfo

Legend:

  • [+] path exists in CPython
  • [x] up-to-date, [ ] outdated

@youknowone youknowone merged commit d2d8eee into RustPython:main Feb 8, 2026
14 checks passed
@youknowone youknowone deleted the _types branch February 8, 2026 10:17
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant