Skip to content

Add strict parameter to map() builtin#7405

Merged
youknowone merged 2 commits intoRustPython:mainfrom
rlaisqls:fix/map-strict-parameter
Mar 12, 2026
Merged

Add strict parameter to map() builtin#7405
youknowone merged 2 commits intoRustPython:mainfrom
rlaisqls:fix/map-strict-parameter

Conversation

@rlaisqls
Copy link
Copy Markdown
Contributor

@rlaisqls rlaisqls commented Mar 12, 2026

  • Implement map(func, *iterables, strict=True) support added in CPython 3.14
  • When strict=True, raises ValueError if iterables have different lengths (analogous to zip(strict=True))
  • Add pickle support (reduce/setstate) for strict state serialization

Summary by CodeRabbit

  • New Features

    • Added strict mode to map(), which validates that all input iterables have matching lengths.
    • map() now exposes a configurable strict flag preserved across serialization/deserialization.
  • Bug Fixes

    • Improved error reporting: raises clear ValueError when iterables are shorter or longer than expected in strict mode.

@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai bot commented Mar 12, 2026

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yml

Review profile: CHILL

Plan: Pro

Run ID: d23125b8-6571-4c2e-812e-9c68dac860ad

📥 Commits

Reviewing files that changed from the base of the PR and between e1a7a29 and bcf3b6c.

📒 Files selected for processing (1)
  • crates/vm/src/builtins/map.rs

📝 Walkthrough

Walkthrough

PyMap gains a configurable strict mode stored atomically, accepted via constructor args, preserved in pickling (reduce/setstate), and enforced during iteration to detect and raise ValueError on input-length mismatches when enabled.

Changes

Cohort / File(s) Summary
PyMap strict mode implementation
crates/vm/src/builtins/map.rs
Added strict: PyAtomic<bool> to PyMap and PyMapNewArgs for constructor args. Updated constructor signature to accept strict, initialized atomically. Added __setstate__ and extended __reduce__ to include strict. Reworked iterator next logic to track per-iterator progress and raise ValueError on shorter/longer input mismatches when strict is true; preserves prior behavior when false.

Sequence Diagram(s)

sequenceDiagram
    participant Caller
    participant PyMap
    participant PyIter as Iterator
    participant VM as VirtualMachine

    Caller->>PyMap: PyMap.new(iterables..., strict=bool)
    PyMap->>PyMap: store strict (PyAtomic<bool>)
    Caller->>PyMap: next()
    PyMap->>PyIter: advance each input iterator
    PyIter-->>PyMap: item or StopIteration / error
    alt strict == true and length mismatch detected
        PyMap->>VM: raise ValueError("map() argument ... is shorter/longer")
        VM-->>Caller: propagate error
    else no mismatch or strict == false
        PyMap->>Caller: return next mapped item or StopIteration
    end
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Poem

🐰 I hopped in code with eager stride,

strictness tucked safely by my side.
When lengths agree, we dance and play,
else I shout "Mismatch!"—no stray buffet. 🥕

🚥 Pre-merge checks | ✅ 2 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 66.67% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (2 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title 'Add strict parameter to map() builtin' accurately and concisely summarizes the main change in the pull request—adding strict mode support to the map() function.

✏️ 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.

Copy link
Copy Markdown
Contributor

@ShaharNaveh ShaharNaveh left a comment

Choose a reason for hiding this comment

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

TY! LGTM

@github-actions
Copy link
Copy Markdown
Contributor

📦 Library Dependencies

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

[x] lib: cpython/Lib/poplib.py
[x] test: cpython/Lib/test/test_poplib.py

dependencies:

  • poplib

dependent tests: (1 tests)

  • poplib: test_poplib

[x] test: cpython/Lib/test/test_builtin.py (TODO: 19)

dependencies:

dependent tests: (no tests depend on builtin)

[x] test: cpython/Lib/test/test_gc.py

dependencies:

dependent tests: (168 tests)

  • gc: test_array test_asyncio test_baseexception test_builtin test_call test_class test_context test_csv test_ctypes test_deque test_descr test_dict test_enum test_enumerate test_functools test_gc test_generators test_gzip test_inspect test_itertools test_logging test_memoryio test_memoryview test_ordered_dict test_peepholer test_pickle test_picklebuffer test_raise test_set test_socket test_ssl test_struct test_subprocess test_sys test_sys_setprofile test_sys_settrace test_tempfile test_tuple test_types test_typing test_unittest test_weakref test_weakset test_winreg test_zoneinfo test_zstd
    • timeit: test_timeit
    • trace: test_trace
    • weakref: test_ast test_asyncio test_code test_concurrent_futures test_contextlib test_copy test_exceptions test_file test_fileio test_frame test_genericalias test_importlib test_io test_ipaddress test_mmap test_queue test_re test_scope test_slice test_sqlite3 test_thread test_threading test_threading_local test_type_params test_unittest test_uuid test_xml_etree
      • asyncio: test_asyncio test_contextlib_async test_os test_unittest
      • bdb: test_bdb
      • concurrent.futures.process: test_compileall test_concurrent_futures
      • copy: test_bytes test_codecs test_collections test_copyreg test_coroutines test_decimal test_defaultdict test_dictviews test_email test_fractions test_http_cookies test_minidom test_opcache test_optparse test_platform test_plistlib test_posix test_site test_statistics test_sysconfig test_tomllib test_urllib2 test_xml_dom_minicompat test_zlib
      • gzip: test_fileinput test_tarfile test_xmlrpc
      • inspect: test_abc test_argparse test_asyncgen test_buffer test_grammar test_monitoring test_ntpath test_operator test_patma test_posixpath test_pydoc test_signal test_sqlite3 test_traceback test_type_annotations test_yield_from test_zipimport
      • logging: test_hashlib test_pkgutil test_support test_urllib2net
      • multiprocessing: test_concurrent_futures test_fcntl test_multiprocessing_main_handling
      • symtable: test_symtable
      • tempfile: test_bz2 test_cmd_line test_compile test_ctypes test_dis test_doctest test_ensurepip test_faulthandler test_filecmp test_httpservers test_importlib test_launcher test_linecache test_mailbox test_pathlib test_pkg test_py_compile test_regrtest test_runpy test_selectors test_shutil test_string_literals test_tabnanny test_termios test_threadedtempfile test_tokenize test_urllib test_urllib_response test_venv test_winconsoleio test_zipapp test_zipfile test_zipfile64
      • xml.sax.expatreader: test_sax

[x] lib: cpython/Lib/symtable.py
[ ] test: cpython/Lib/test/test_symtable.py (TODO: 17)

dependencies:

  • symtable

dependent tests: (2 tests)

  • symtable: test_inspect test_symtable

Legend:

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

Copy link
Copy Markdown
Contributor

@moreal moreal left a comment

Choose a reason for hiding this comment

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

Thank you for your first contribution!

Copy link
Copy Markdown
Member

@youknowone youknowone left a comment

Choose a reason for hiding this comment

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

Thank you so much! and welcome to RustPython project

@youknowone youknowone enabled auto-merge (squash) March 12, 2026 14:44
@youknowone youknowone merged commit 61b3b4f into RustPython:main Mar 12, 2026
28 of 29 checks passed
youknowone pushed a commit to youknowone/RustPython that referenced this pull request Mar 19, 2026
* Add strict parameter to map() builtin

* Refactor map IterNext to match zip style
youknowone pushed a commit to youknowone/RustPython that referenced this pull request Mar 22, 2026
* Add strict parameter to map() builtin

* Refactor map IterNext to match zip style
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.

4 participants