python-voting/voting/quorum.py

55 lines
1.6 KiB
Python
Raw Permalink Normal View History

2023-04-03 03:07:00 +00:00
from dataclasses import dataclass
from enum import Enum
from typing import Dict, Union
class QuorumKind(Enum):
"""QuorumKind defines the kind of quorum.
Kinds:
- NONE - there ain't no quorum
- ABSOLUTE - absolute number of minimum voters is required
- PERCENT - minimum percentage of valid voters must have voted
"""
NONE = 0
ABSOLUTE = 1
PERCENT = 2
@dataclass
class Quorum:
"""Quorm defines the required quorum of a Voting.
Absolute quorums must be greater than 0.
Percent quorums must be greather than 0.0 and less then or equal to 100.0.
"""
kind: QuorumKind
value: Union[int, float]
def __init__(self, kind: QuorumKind = None, value: Union[float, int, None] = None):
super(Quorum)
if kind is None:
self.kind = QuorumKind.NONE
elif isinstance(kind, str):
self.kind = QuorumKind[kind]
else:
self.kind = kind
if self.kind == QuorumKind.NONE:
self.value = 0
elif self.kind == QuorumKind.ABSOLUTE:
self.value = int(value)
if self.value <= 0:
raise ValueError(f"Value can not be less than or equal to zero: {self.value}")
elif self.kind == QuorumKind.PERCENT:
self.value = float(value)
if self.value <= 0.0 or self.value > 100.0:
raise ValueError(f"Value must be greater than 0.0 and less then or equal to 100.0: {self.value}")
def as_dict(self) -> Dict:
return {
"kind": self.kind.name,
"value": self.value,
}