Cirq icon indicating copy to clipboard operation
Cirq copied to clipboard

Mypy raises type check errors with default argument to Cirq protocols

Open tanujkhattar opened this issue 3 years ago • 1 comments

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/mypy does not detect this error.
  • [ ] Fix the type annotations on default parameter of protocols. (eg: by using the overload + optional signature for default).

Cirq version 0.14dev

tanujkhattar avatar Feb 14 '22 19:02 tanujkhattar

Cirq cynq: not terribly high-priority, but we should at least confirm that mypy isn't skipping files/directories.

95-martin-orion avatar Feb 16 '22 19:02 95-martin-orion

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.

mhucka avatar Oct 16 '25 04:10 mhucka