Skip to content

negative-to-unsigned conversions are inconsistent between ValueError and OverflowError #6116

Description

@davidhewitt

The following test fails inconsistently on various Python versions. See also #6016 (comment)

diff --git a/src/conversions/std/num.rs b/src/conversions/std/num.rs
index 2fca7aa9f..207249246 100644
--- a/src/conversions/std/num.rs
+++ b/src/conversions/std/num.rs
@@ -920,6 +920,17 @@ mod tests {
                     let obj = val.into_pyobject(py).unwrap();
                     assert_eq!(obj.extract::<$t>().unwrap(), val as $t);});
                 }
+
+                #[test]
+                fn test_negative() {
+                    Python::attach(|py| {
+                        let obj = py.eval(c"-1", None, None).unwrap();
+                        match obj.extract::<$t>() {
+                            Ok(val) => assert_eq!(val, <$t>::try_from(-1i8).unwrap()),
+                            Err(err) => assert!(err.is_instance_of::<exceptions::PyValueError>(py)),
+                        };
+                    });
+                }
             }
         )
     );

Note that older CPython APIs such as PyLong_AsUnsignedLong use OverflowError, and newer APIs such as PyLong_AsUInt64 use ValueError.

I think we should match the convention of the newer CPython APIs and use ValueError as the error message. However there is possibly an argument that we should instead accept this divergence and have a clean split between (say) 3.14+ using ValueError and older versions using OverflowError.

See also #5179 which is related here.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    Fields

    No fields configured for Bug.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions