Skip to content

Type checking of UnitRegistry instance calls are potentially broken, or return values are mistyped. #1642

@cgevans

Description

@cgevans

Changes in Quantity mean that basic methods on Quantity instances returned by calls to a UnitRegistry now result in typechecking errors in mypy. In our code, it breaks check and m_as. This does not occur if ureg.Quantity is called instead.

This may be caused by calls to UnitRegistry directly potentially not being Quantity instances (they can simply be numbers), and so the type checking here might be an improvement, but it also appears that those calls are documented as returning a Quantity ("Parse a mathematical expression including units and return a quantity object."), so there appears to be either a problem of function or of documentation here, and it appears that the type hinting within pint may be incorrectly stating that the calls return a Quantity.

This appears to be caused by c082656, and so is present in 0.19.3 and later.

A minimal example:

import pint
ureg = pint.UnitRegistry()
q = ureg("1 m")
q2 = ureg.Quantity("1 m")
q3 = ureg.Quantity("1")
q4 = ureg("1")
q.check("m")
q2.check("m")
q3.check("")
q4.check("")

Results in mypy error: error: Quantity? has no attribute "check" for q.check and q4.check, and no error for q2.check. q4.check also fails, because q4 is an int.

(Note that the Quantity to PlainQuantity change also breaks quite a bit of typechecking downstream, for anyone who was using a TypeVar with the quantity. However, this is fixable by replacing Quantity with PlainQuantity.)

Metadata

Metadata

Assignees

No one assigned

    Labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions