Skip to content

Instantly share code, notes, and snippets.

@blakeNaccarato
Last active January 13, 2024 01:16
Show Gist options
  • Save blakeNaccarato/3654f603a800917e4aea762a8c00a563 to your computer and use it in GitHub Desktop.
Save blakeNaccarato/3654f603a800917e4aea762a8c00a563 to your computer and use it in GitHub Desktop.
Pint intricacies

Pint intricacies

Type checkers assume that sums of Quantity can be datetime

Problem

There must be an @overload on __add__ somewhere in pint which unintentionally matches to datetime. If two quantities are added, unit checkers artificially restrict allowable operations to those supported by datetime.

from pint import UnitRegistry
U = UnitRegistry()
Q = U.Quantity
sum_of_units = Q(1,"in") + Q(2,"in")
other = sum_of_units / 2  # Type checker complains that we can't use "/"

Workaround

Wrap any sums of quantities in another Quantity call.

...
sum_of_units = Q(Q(1,"in") + Q(2,"in"))  # <-- We wrapped our sum in another call to Q
other = sum_of_units / 2  # No more complaints
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment