Skip to content

Common ValueError raised when formatting complex numbers #551

Open
@robtovey

Description

@robtovey

Describe the bug
Attempts to format the number 1-1j will result in a ValueError raised. This is due to a feature (bug?) in CPython:

x = 1+-1j # this does not raise an error
x = complex("1+-1j") # this raises a ValueError

Unfortunately this case must be hit quite frequently in these lines of code:

deepdiff/deepdiff/helper.py

Lines 431 to 446 in ecc823a

elif isinstance(number, only_complex_number): # type: ignore
# Case for complex numbers.
number = number.__class__(
"{real}+{imag}j".format( # type: ignore
real=number_to_string(
number=number.real, # type: ignore
significant_digits=significant_digits,
number_format_notation=number_format_notation
),
imag=number_to_string(
number=number.imag, # type: ignore
significant_digits=significant_digits,
number_format_notation=number_format_notation
)
) # type: ignore
)

To Reproduce

from deepdiff.helper import number_to_string
print(number_to_string(1-1j, significant_digits=1)) # raises a ValueError

Expected behavior
I expect this to print 1.0-1.0j, not raise an error!

I am using

  • Python 3.12
  • DeepDiff on main

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions