Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Type hint improvements #194

Merged

Conversation

MarquessV
Copy link
Contributor

Some fixes and improvements influenced by resolving some mypy issues in pyQuil#1566.

def __new__(
cls,
operator: ArithmeticOperator,
destination: ArithmeticOperand,
source: ArithmeticOperand,
) -> "Arithmetic": ...
) -> Self: ...
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This fixes an issue where mypy would expect a sub class to return an instance of itself even when leaning on it's parent class for initialization. For exampe:

class Base:
    def __new__(cls) -> "Base": ...

class Sub(Base):
    def __new__(cls) -> "Sub":
        return super().__new__(cls)  # mypy complains that the function should return `Sub` but it returns `Base`

The above is valid code, an instance of Sub() would work as you would expect Sub to work, and calling super().__new__ to initialize a subclass is what the Python docs recommend.

The Self type is essentially a shortcut for a generic TypeVar bounded by the parent class, meaning that a return type of Self can be used in a child class without violating any type rules.

parameters: Sequence[Expression],
qubits: Sequence[Qubit],
instructions: Sequence[Instruction],
modifiers: Sequence[GateModifier],
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Accepting Sequence instead of List makes these type hints more flexible. A List is a Sequence, and pyo3 converts Sequences to Rust Vecs, so this doesn't betray the reality of the bindings.

@MarquessV MarquessV merged commit 16d0401 into 1455-python-support-for-program-and-beyond Apr 19, 2023
@MarquessV MarquessV deleted the v4-type-hint-improvements branch April 19, 2023 16:09
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