Skip to content

Make Quantity comparisons less error prone #12

@llucax

Description

@llucax

What's needed?

We need to make it as hard as possible for users to shot themselves in the foot.

Allowing == comparisons with Quantitys is generally unsafe, because it uses a float underneath.

Proposed solution

Disallow using == with Quantitys.

Ideally it should be rejected by the type system (mypy), but it should also raise an exception (or return NotImplemented if type checking is not used). If possible users should be redirected to using Quantity.isclose() instead.

Ideally isclose() should probably handle 0 (or values close to 0) specially, as documented in math.isclose.

Users can always escape this by accessing the raw float and using == with that in weird cases where == might be necessary, but that should be considered a low-level operation.

Use cases

This came up when trying to see if a battery pool is full or empty. Naturally one would do soc == Percentage(100), but this could have issues if the soc calculation has some precision issue and it is something like 99.999999 instead. But this problem is much more general than that, users should always try to think in terms of isclose() instead of strict equality with floats.

Metadata

Metadata

Assignees

No one assigned

    Labels

    type:enhancementNew feature or enhancement visitble to users

    Type

    No type

    Projects

    Status

    To do

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions