Mypy raises type check errors with default argument to Cirq protocols
Description of the issue This came up while reviewing https://github.com/quantumlib/Cirq/pull/4881 and offline discussions with @Zshan0.
A common pattern used throughout cirq protocols is to take a default: TDefault parameter which should be returned if the protocol does not succeed, or raise a type error if no explicit default has been provided. For example:
https://github.com/quantumlib/Cirq/blob/87d36326842a025ee07cd9d61f87b259846328c6/cirq-core/cirq/protocols/unitary_protocol.py#L42-L44
https://github.com/quantumlib/Cirq/blob/87d36326842a025ee07cd9d61f87b259846328c6/cirq-core/cirq/protocols/unitary_protocol.py#L89-L91
However, this construct actually raises a mypy error and is a known issue -- https://github.com/python/mypy/issues/8739
How to reproduce the issue
Here is a minimal failing example that follows a similar construct:
TDefault = TypeVar('TDefault')
RaiseTypeErrorIfNotProvided: List = []
def unitary(val: Any, default: TDefault = RaiseTypeErrorIfNotProvided) -> Union[List, TDefault]:
return default
https://mypy-play.net/?mypy=latest&python=3.10&gist=f60ce6c21997d6559f0bf5bbe0881230
Summary There are two different issues here that need to fixed:
- [ ] Figure out and fix why
./check/mypydoes not detect this error. - [ ] Fix the type annotations on
defaultparameter of protocols. (eg: by using the overload + optional signature for default).
Cirq version 0.14dev
Cirq cynq: not terribly high-priority, but we should at least confirm that mypy isn't skipping files/directories.
The type declarations on the code in question have been changed since this issue was opened, and the current code does not have this problem, so I think at some point it was fixed. Closing this issue as completed.