cattrs icon indicating copy to clipboard operation
cattrs copied to clipboard

Raise on input/tuple-args length mis-match

Open EpicWink opened this issue 3 years ago • 6 comments

When structuring a heterogeneous tuple, if the input has too few or many elements, this PR now raises an error. The error is a ValueError in non-detailed validation.

Two existing tuple-structuring tests had to be fixed (in the zero-element case).

Fixes #57

EpicWink avatar Jul 04 '22 11:07 EpicWink

Hello, thanks for contributing.

Unfortunately this PR makes the happy path almost twice slower.

$ pyperf timeit -g -s 'from cattrs import structure; t = tuple[int, str];v = [1, 2]' 'structure(v, t)'
old: Mean +- std dev: 1.50 us +- 0.04 us
new: Mean +- std dev: 2.94 us +- 0.14 us

# Detailed validation false:
old: Mean +- std dev: 1.39 us +- 0.06 us
new: Mean +- std dev: 1.95 us +- 0.09 us

You're overcomplicating it with the _zip_strict thing. One length comparison after the transformation should be enough, right?

Tinche avatar Jul 04 '22 17:07 Tinche

One length comparison after the transformation should be enough, right?

The one case that that doesn't solve is when obj is a un-sized iterable with more values than the tuple type. If you're fine with that trade-off, then I'll make the change

EpicWink avatar Jul 04 '22 22:07 EpicWink

What is an un-sized operable with Moreno values?

Tinche avatar Jul 04 '22 23:07 Tinche

What is an un-sized operable with Moreno values?

Ah, autocorrect. I've updated my previous message

EpicWink avatar Jul 05 '22 02:07 EpicWink

Doing the post-check comparing the result length with the input (latest commit) gives benchmark results:

  • Detailed validation:
    • Before: 1.96 ± 0.14 μs
    • After: 2.10 ± 0.15 μs
  • Not-detailed validation:
    • Before: 1.83 ± 0.09 μs
    • After: 1.98 ± 0.16 μs

EpicWink avatar Jul 05 '22 05:07 EpicWink

Codecov Report

Merging #283 (75fdc3d) into main (b1a681a) will increase coverage by 0.04%. The diff coverage is 100.00%.

:exclamation: Current head 75fdc3d differs from pull request most recent head 8354a76. Consider uploading reports for the commit 8354a76 to get more accurate results

@@            Coverage Diff             @@
##             main     #283      +/-   ##
==========================================
+ Coverage   97.01%   97.05%   +0.04%     
==========================================
  Files          16       16              
  Lines        1339     1358      +19     
==========================================
+ Hits         1299     1318      +19     
  Misses         40       40              
Impacted Files Coverage Δ
src/cattrs/converters.py 98.26% <100.00%> (+0.08%) :arrow_up:

:mega: Codecov can now indicate which changes are the most critical in Pull Requests. Learn more

codecov-commenter avatar Jul 05 '22 05:07 codecov-commenter

I'll merge this in now. I might work on it a little more myself. Thanks!

Tinche avatar Sep 11 '22 22:09 Tinche