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

ENH: make Parity.value of type Literal[-1, 1] #263

Merged
merged 1 commit into from
Apr 24, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions docs/conf.py
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,7 @@ def create_constraints_inventory() -> None:
"qrules.topology.NodeType": "typing.TypeVar",
"SpinFormalism": ("obj", "qrules.transition.SpinFormalism"),
"StateDefinition": ("obj", "qrules.combinatorics.StateDefinition"),
"typing.Literal[-1, 1]": "typing.Literal",
}
api_target_types: dict[str, str | tuple[str, str]] = {
"qrules.combinatorics.InitialFacts": "obj",
Expand Down
28 changes: 16 additions & 12 deletions src/qrules/quantum_numbers.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,34 +8,38 @@

from __future__ import annotations

import sys
from decimal import Decimal
from fractions import Fraction
from functools import total_ordering
from typing import Any, Generator, NewType, Union

import attrs
from attrs import field, frozen
from attrs.validators import instance_of

from qrules._implementers import implement_pretty_repr

if sys.version_info < (3, 8):
from typing_extensions import Literal
else:
from typing import Literal

def _check_plus_minus(_: Any, __: attrs.Attribute, value: Any) -> None:

def _to_parity(value: int) -> Literal[-1, 1]:
if not isinstance(value, int):
msg = (
f"Input for {Parity.__name__} has to be of type {int.__name__}, not"
f" {type(value).__name__}"
)
msg = f"Parity must be an integer, not {type(value)}"
raise TypeError(msg)
if value not in {-1, +1}:
msg = f"Parity can only be +1 or -1, not {value}"
raise ValueError(msg)
if value == -1:
return -1
if value == +1:
return 1
msg = f"Parity can only be +1 or -1, not {value}"
raise ValueError(msg)


@total_ordering
@frozen(eq=False, hash=True, order=False, repr=False)
class Parity: # noqa: PLW1641
value: int = field(validator=[instance_of(int), _check_plus_minus])
value: Literal[-1, 1] = field(converter=_to_parity)

def __eq__(self, other: object) -> bool:
if isinstance(other, Parity):
Expand All @@ -47,7 +51,7 @@ def __gt__(self, other: Any) -> bool:
return True
return self.value > int(other)

def __int__(self) -> int:
def __int__(self) -> Literal[-1, 1]:
return self.value

def __neg__(self) -> Parity:
Expand Down
Loading