Skip to content

[Typing] Python type stubs for common functions of quantity and dimensionality - #206

Merged
apdavison merged 12 commits into
python-quantities:masterfrom
codingchipmunk:typing
Apr 5, 2023
Merged

apdavison merged 12 commits into
python-quantities:masterfrom
codingchipmunk:typing

Conversation

@codingchipmunk

Copy link
Copy Markdown
Contributor

Hello everyone,

I wrote some stub files containing type hints for some of the functions. My goals for this PR were:

  • Make it more transparent to the user (and code analysis tools) that the subscript operator does not return a single (primitive) value, but another Quantity object, which in turn IS another numpy array by inheritance.
  • Make it possible to track the class conversions done by arithmetic operations

Cheers,
Peter

@apdavison

Copy link
Copy Markdown
Contributor

Hi Peter, many thanks for this.

Running mypy quantities in the root directory gives 183 errors. Is this something you'd have time to look into?

@codingchipmunk

Copy link
Copy Markdown
Contributor Author

Hello Andrew,
I just had a look and was able to solve multiple conflicts, some happened because I didn't create stubs for everything. After adding the missing stubs, I am now down to 126 errors. 105 errors come from MyPy being unable to determine the type of the units in quantities/units/ files, I am currently investigating the reason for that.

The other errors are stem mostly from type conflicts (12 errors), which may occur because I simply inferred the wrong types when defining the type-stubs. 4 errors are because of incompatible imports, which may require a separate issue / pull request to fix, because they require some code refactoring to fix. 2 errors are because imported names are redefined (also requires refactoring).

A huge problem when annotating this library stems from inheritance (e.g. from the built-in dict or NumPy types) and the Liskov substitution principle (LSP) which MyPy enforces. So we have to annotate functions which override sources with more general types as we would need; In LSP an overridden function may only change the parameter signature to use more generic types and return types may only be narrowed. This is becoming a problem in some places like the Dimensionality.__hash__ function and multiple arithmetic functions of Quantity, where some signatures of ndarray are very complex:

quantities/quantity.pyi:69: error: Signature of "__sub__" incompatible with supertype "ndarray"
quantities/quantity.pyi:69: note:      Superclass:
quantities/quantity.pyi:69: note:          @overload
quantities/quantity.pyi:69: note:          def __sub__(self, Union[_SupportsArray[dtype[bool_]], _NestedSequence[_SupportsArray[dtype[bool_]]], bool, _NestedSequence[bool]]) -> NoReturn
quantities/quantity.pyi:69: note:          @overload
quantities/quantity.pyi:69: note:          def __sub__(self, Union[_SupportsArray[dtype[Union[bool_, unsignedinteger[Any]]]], _NestedSequence[_SupportsArray[dtype[Union[bool_, unsignedinteger[Any]]]]], bool, _NestedSequence[bool]]) -> ndarray[Any, dtype[unsignedinteger[Any]]]
quantities/quantity.pyi:69: note:          @overload
quantities/quantity.pyi:69: note:          def __sub__(self, Union[_SupportsArray[dtype[Union[bool_, integer[Any]]]], _NestedSequence[_SupportsArray[dtype[Union[bool_, integer[Any]]]]], bool, int, _NestedSequence[Union[bool, int]]]) -> ndarray[Any, dtype[signedinteger[Any]]]
quantities/quantity.pyi:69: note:          @overload
quantities/quantity.pyi:69: note:          def __sub__(self, Union[_SupportsArray[dtype[Union[bool_, integer[Any], floating[Any]]]], _NestedSequence[_SupportsArray[dtype[Union[bool_, integer[Any], floating[Any]]]]], bool, int, float, _NestedSequence[Union[bool, int, float]]]) -> ndarray[Any, dtype[floating[Any]]]
quantities/quantity.pyi:69: note:          @overload
quantities/quantity.pyi:69: note:          def __sub__(self, Union[_SupportsArray[dtype[Union[bool_, integer[Any], floating[Any], complexfloating[Any, Any]]]], _NestedSequence[_SupportsArray[dtype[Union[bool_, integer[Any], floating[Any], complexfloating[Any, Any]]]]], bool, int, float, complex, _NestedSequence[Union[bool, int, float, complex]]]) -> ndarray[Any, dtype[complexfloating[Any, Any]]]
quantities/quantity.pyi:69: note:          @overload
quantities/quantity.pyi:69: note:          def __sub__(self, Union[_SupportsArray[dtype[Union[bool_, number[Any]]]], _NestedSequence[_SupportsArray[dtype[Union[bool_, number[Any]]]]], bool, int, float, complex, _NestedSequence[Union[bool, int, float, complex]]]) -> ndarray[Any, dtype[number[Any]]]
quantities/quantity.pyi:69: note:          @overload
quantities/quantity.pyi:69: note:          def __sub__(self, Union[_SupportsArray[dtype[Union[bool_, integer[Any], timedelta64]]], _NestedSequence[_SupportsArray[dtype[Union[bool_, integer[Any], timedelta64]]]], bool, int, _NestedSequence[Union[bool, int]]]) -> ndarray[Any, dtype[timedelta64]]
quantities/quantity.pyi:69: note:          @overload
quantities/quantity.pyi:69: note:          def __sub__(self, Union[_SupportsArray[dtype[Union[bool_, integer[Any], timedelta64]]], _NestedSequence[_SupportsArray[dtype[Union[bool_, integer[Any], timedelta64]]]], bool, int, _NestedSequence[Union[bool, int]]]) -> ndarray[Any, dtype[datetime64]]
quantities/quantity.pyi:69: note:          @overload
quantities/quantity.pyi:69: note:          def __sub__(self, Union[_SupportsArray[dtype[datetime64]], _NestedSequence[_SupportsArray[dtype[datetime64]]]]) -> ndarray[Any, dtype[timedelta64]]
quantities/quantity.pyi:69: note:          @overload
quantities/quantity.pyi:69: note:          def __sub__(self, Any) -> Any
quantities/quantity.pyi:69: note:          @overload
quantities/quantity.pyi:69: note:          def __sub__(self, Union[_SupportsArray[dtype[object_]], _NestedSequence[_SupportsArray[dtype[object_]]]]) -> Any
quantities/quantity.pyi:69: note:      Subclass:
quantities/quantity.pyi:69: note:          def __sub__(self, Any) -> Quantity

So we should discuss how we want to deal with these issues. The fastest method would be to suppress this kind of errors by adding # type: ignore to the definition-line of the affected functions, however I wouldn't call that "clean code".

@apdavison

Copy link
Copy Markdown
Contributor

Many thanks for this follow-up, Peter. Based on the aphorism "perfect is the enemy of good", I would support using # type: ignore for the LSP-related errors, but with a "todo" comment in each case, and a Github issue so that we don't forget to address this in future.

@codingchipmunk

Copy link
Copy Markdown
Contributor Author

Ok, so I didn't have time to work on this in the past few months, but I am back.

I annotated some stuff to with the ignore comments and generated pyi-stubs for all units (since there were some variables which produced weird errors where mypy was unable to defer their type).

The remaining (and new errors) go now much more into the depth of how the module is structured.

quantities/units/volume.pyi:21: error: Name "milliliter" already defined on line 8  [no-redef]
quantities/units/pressure.pyi:38: error: Name "barad" already defined on line 37  [no-redef]
quantities/units/__init__.py:75: error: Incompatible import of "pt" (imported name has type "UnitQuantity", local name has type "UnitLength")  [assignment]
quantities/typing/quantities.pyi:8: error: Type argument "Union[float, int]" of "dtype" must be a subtype of "generic"  [type-var]
quantities/__init__.py:283: error: Incompatible import of "dimensionless" (imported name has type Module, local name has type "Dimensionless")  [assignment]
quantities/__init__.py:287: error: Incompatible import of "dimensionless" (imported name has type Module, local name has type "Dimensionless")  [assignment]
quantities/constants/mathematical.py:15: error: Argument "aliases" to "UnitConstant" has incompatible type "str"; expected "List[str]"  [arg-type]
quantities/tests/test_methods.py:188: error: Name "test_nanargmax" already defined on line 163  [no-redef]

Short breakdown:

  • Line 3 may be an actual error, which is now caught by mypy
  • Line 7 also may be an actual error
  • Everything else seems to be confusion, caused by the way the imports are working

One cause may be, that mypy doesn't pick up on the removal of imported constants at the end of the files where units are defined. To investigate this, I tried to get rid of the direct imports by importing the modules and using the constants only as a reference (i.e. instead of from .energy import J and then using it as a = 10*J, import the module energy and use it as a = 10*energy.J). This is more verbose, but it gets rid of the del statements at the end of the files and the possibility to miss deleting some constants. Also I don't think it makes sense to delete the definition of the class UnitQuantity at the end of each file, as this is just a class.

Long story short: I don't think you can do this with relative imports and have a consistent import style at the same time. Example from power.py:

# file quantities/units/power.py
from . import time # (ok) imports the module quantities.units.time 
from . import force # (nok) imports the constant quantities.units.acceleration.force as it is exported in units/__init__.py
import time # (nok) imports the module time from stdlib
import force # (ok) imports the module quantities.units.force

As far as I am aware, the only way to do this consistently would be to use absolute imports. I don't know if you want to do this, but I think if we do it for the units, we should also do it for everything else, so there is a consistent style across the project.

@apdavison
apdavison merged commit 4717f22 into python-quantities:master Apr 5, 2023
@apdavison

Copy link
Copy Markdown
Contributor

Many thanks for all your work on this @codingchipmunk

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants