Complex numbers inconsistency

While experimenting with complex numbers, I encountered an unexpected outcome:

>>> (2+2j).imag
2.0
>>> 2+2j.imag
4.0

The first result is as expected, but the second one is not. It appears to have been computed as (2+2)j for reasons that are unclear.

>>> 2+2j.real
2.0
>>> 2+2j.imag
4.0

While accessing real, everything is well. However, when attempting to access imag, the unexpected result is returned.

What might cause this inconsistency?

I am concerned about the potential occurrence of this inconsistency in other cases, which could potentially lead to inaccurate calculations.

You are computing this:

In [2]: 2+(2j.imag)
Out[2]: 4.0

No; it’s computed as 2 + (2j.imag). Attribute access has higher precedence than arithmetic operators, and the + is an actual operator, not part of a literal syntax for the complex value.

This is a well-known issue that has been fairly commonly asked about, and there isn’t an obvious way to fix it without breaking anything else.

When puzzled by an expression involving at least 2 operations, think about priority.
When in doubt about operation priority, parenthesize.