Skip to content

Commit

Permalink
ENH: make Parity.value of type Literal[-1, 1]
Browse files Browse the repository at this point in the history
  • Loading branch information
redeboer committed Apr 24, 2024
1 parent ae2b211 commit fa3a95a
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 15 deletions.
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
32 changes: 17 additions & 15 deletions src/qrules/quantum_numbers.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,34 +8,36 @@

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
from typing import Any, Generator, NewType, SupportsInt, 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:
if not isinstance(value, int):
msg = (
f"Input for {Parity.__name__} has to be of type {int.__name__}, not"
f" {type(value).__name__}"
)
raise TypeError(msg)
if value not in {-1, +1}:
msg = f"Parity can only be +1 or -1, not {value}"
raise ValueError(msg)

def _to_parity(value: SupportsInt) -> Literal[-1, 1]:
value = int(value)
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 +49,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

0 comments on commit fa3a95a

Please sign in to comment.