quantumlib / Cirq

A Python framework for creating, editing, and invoking Noisy Intermediate Scale Quantum (NISQ) circuits.
Apache License 2.0
4.26k stars 1.01k forks source link

mypy type check errors with default argument to cirq protocols. #4992

Open tanujkhattar opened 2 years ago

tanujkhattar commented 2 years ago

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:

Cirq version 0.14dev

95-martin-orion commented 2 years ago

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