Skip to content

Commit 8de95ab

Browse files
authored
Improve Python Code Formatting and Quality (#94)
* Fix setup.cfg * Refactor Python codes with Ruff and manual fixing.
1 parent 18af554 commit 8de95ab

18 files changed

+287
-229
lines changed

python/benchmark.py

Lines changed: 8 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,32 +1,34 @@
11
import time
22
from itertools import combinations
33

4-
from phevaluator import _evaluate_cards, _evaluate_omaha_cards, sample_cards
4+
from phevaluator import _evaluate_cards
5+
from phevaluator import _evaluate_omaha_cards
6+
from phevaluator import sample_cards
57

68

7-
def evaluate_all_five_card_hands():
9+
def evaluate_all_five_card_hands() -> None:
810
for cards in combinations(range(52), 5):
911
_evaluate_cards(*cards)
1012

1113

12-
def evaluate_all_six_card_hands():
14+
def evaluate_all_six_card_hands() -> None:
1315
for cards in combinations(range(52), 6):
1416
_evaluate_cards(*cards)
1517

1618

17-
def evaluate_all_seven_card_hands():
19+
def evaluate_all_seven_card_hands() -> None:
1820
for cards in combinations(range(52), 7):
1921
_evaluate_cards(*cards)
2022

2123

22-
def evaluate_random_omaha_card_hands():
24+
def evaluate_random_omaha_card_hands() -> None:
2325
total = 100_000
2426
for _ in range(total):
2527
cards = sample_cards(9)
2628
_evaluate_omaha_cards(cards[:5], cards[5:])
2729

2830

29-
def benchmark():
31+
def benchmark() -> None:
3032
print("--------------------------------------------------------------------")
3133
print("Benchmark Time")
3234
t = time.process_time()

python/examples.py

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,8 @@
1-
from phevaluator import evaluate_cards, evaluate_omaha_cards
1+
from phevaluator import evaluate_cards
2+
from phevaluator import evaluate_omaha_cards
23

34

4-
def example1():
5+
def example1() -> None:
56
print("Example 1: A Texas Holdem example")
67

78
a = 7 * 4 + 0 # 9c
@@ -26,7 +27,7 @@ def example1():
2627
print("Player 2 has a stronger hand")
2728

2829

29-
def example2():
30+
def example2() -> None:
3031
print("Example 2: Another Texas Holdem example")
3132

3233
rank1 = evaluate_cards("9c", "4c", "4s", "9d", "4h", "Qc", "6c") # expected 292
@@ -37,7 +38,7 @@ def example2():
3738
print("Player 2 has a stronger hand")
3839

3940

40-
def example3():
41+
def example3() -> None:
4142
print("Example 3: An Omaha poker example")
4243
# fmt: off
4344
rank1 = evaluate_omaha_cards(

python/phevaluator/__init__.py

Lines changed: 7 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,14 @@
11
"""Package for evaluating a poker hand."""
2-
from . import hash as hash_ # FIXME: `hash` collides to built-in function
32

3+
from typing import Any
44

55
# import mapping to objects in other modules
66
all_by_module = {
77
"phevaluator": ["card", "evaluator_omaha", "evaluator", "hash", "tables", "utils"],
88
"phevaluator.card": ["Card"],
99
"phevaluator.evaluator": ["_evaluate_cards", "evaluate_cards"],
1010
"phevaluator.evaluator_omaha": ["_evaluate_omaha_cards", "evaluate_omaha_cards"],
11-
"phevaluator.utils": ["sample_cards"]
11+
"phevaluator.utils": ["sample_cards"],
1212
}
1313

1414
# Based on werkzeug library
@@ -21,10 +21,11 @@
2121

2222

2323
# Based on https://peps.python.org/pep-0562/ and werkzeug library
24-
def __getattr__(name):
25-
"""lazy submodule imports"""
24+
def __getattr__(name: str) -> Any: # noqa: ANN401
25+
"""Lazy submodule imports."""
2626
if name in object_origins:
2727
module = __import__(object_origins[name], None, None, [name])
2828
return getattr(module, name)
29-
else:
30-
raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
29+
30+
msg = f"module {__name__!r} has no attribute {name!r}"
31+
raise AttributeError(msg)

python/phevaluator/card.py

Lines changed: 34 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,9 @@
11
"""Module for card."""
2+
23
from __future__ import annotations
34

4-
from typing import Any, Union
5+
6+
CARD_DESCRIPTION_LENGTH = 2
57

68
# fmt: off
79
rank_map = {
@@ -10,7 +12,7 @@
1012
}
1113
suit_map = {
1214
"C": 0, "D": 1, "H": 2, "S": 3,
13-
"c": 0, "d": 1, "h": 2, "s": 3
15+
"c": 0, "d": 1, "h": 2, "s": 3,
1416
}
1517
# fmt: on
1618

@@ -63,33 +65,33 @@ class Card:
6365
The string parameter of the constructor should be exactly 2 characters.
6466
6567
>>> Card("9h") # OK
66-
>>> Card("9h ") # ERROR
68+
>>> Card("9h ") # ERROR
6769
6870
TypeError: Construction with unsupported type
6971
The parameter of the constructor should be one of the following types: [int,
7072
str, Card].
71-
>>> Card(0) # OK. The 0 stands 2 of Clubs
72-
>>> Card("2c") # OK
73-
>>> Card("2C") # OK. Capital letter is also accepted.
74-
>>> Card(Card(0)) # OK
75-
>>> Card(0.0) # ERROR. float is not allowed
73+
>>> Card(0) # OK. The 0 stands 2 of Clubs
74+
>>> Card("2c") # OK
75+
>>> Card("2C") # OK. Capital letter is also accepted.
76+
>>> Card(Card(0)) # OK
77+
>>> Card(0.0) # ERROR. float is not allowed
7678
7779
TypeError: Setting attribute
7880
>>> c = Card("2c")
79-
>>> c.__id = 1 # ERROR
80-
>>> c._Card__id = 1 # ERROR
81+
>>> c.__id = 1 # ERROR
82+
>>> c._Card__id = 1 # ERROR
8183
8284
TypeError: Deliting attribute
8385
>>> c = Card("2c")
84-
>>> del c.__id # ERROR
85-
>>> del c._Card__id # ERROR
86+
>>> del c.__id # ERROR
87+
>>> del c._Card__id # ERROR
8688
8789
"""
8890

8991
__slots__ = ["__id"]
9092
__id: int
9193

92-
def __init__(self, other: Union[int, str, Card]):
94+
def __init__(self, other: int | str | Card) -> None:
9395
"""Construct card object.
9496
9597
If the passed argument is integer, it's set to `self.__id`.
@@ -128,7 +130,7 @@ def id_(self) -> int:
128130
return self.__id
129131

130132
@staticmethod
131-
def to_id(other: Union[int, str, Card]) -> int:
133+
def to_id(other: int | str | Card) -> int:
132134
"""Return the Card ID integer as API.
133135
134136
If the passed argument is integer, it's returned with doing nothing.
@@ -149,17 +151,20 @@ def to_id(other: Union[int, str, Card]) -> int:
149151
"""
150152
if isinstance(other, int):
151153
return other
152-
elif isinstance(other, str):
153-
if len(other) != 2:
154-
raise ValueError(f"The length of value must be 2. passed: {other}")
154+
if isinstance(other, str):
155+
if len(other) != CARD_DESCRIPTION_LENGTH:
156+
msg = (
157+
f"The length of value must be {CARD_DESCRIPTION_LENGTH}. "
158+
f"passed: {other}"
159+
)
160+
raise ValueError(msg)
155161
rank, suit, *_ = tuple(other)
156162
return rank_map[rank] * 4 + suit_map[suit]
157-
elif isinstance(other, Card):
163+
if isinstance(other, Card):
158164
return other.id_
159165

160-
raise TypeError(
161-
f"Type of parameter must be int, str or Card. passed: {type(other)}"
162-
)
166+
msg = f"Type of parameter must be int, str or Card. passed: {type(other)}"
167+
raise TypeError(msg)
163168

164169
def describe_rank(self) -> str:
165170
"""Calculate card rank.
@@ -212,7 +217,7 @@ def describe_card(self) -> str:
212217
"""
213218
return self.describe_rank() + self.describe_suit()
214219

215-
def __eq__(self, other: Any) -> bool:
220+
def __eq__(self, other: object) -> bool:
216221
"""Return equality. This is special method.
217222
218223
Args:
@@ -262,10 +267,12 @@ def __hash__(self) -> int:
262267
"""int: Special method for `hash(self)`."""
263268
return hash(self.id_)
264269

265-
def __setattr__(self, name: str, value: Any) -> None:
266-
"""Set an attribute. This causes TypeError since assignment to attribute is prevented."""
267-
raise TypeError("Card object does not support assignment to attribute")
270+
def __setattr__(self, name: str, value: object) -> None:
271+
"""Set an attribute. This causes TypeError since assignment is prevented."""
272+
msg = "Card object does not support assignment to attribute"
273+
raise TypeError(msg)
268274

269275
def __delattr__(self, name: str) -> None:
270-
"""Delete an attribute. This causes TypeError since deletion of attribute is prevented."""
271-
raise TypeError("Card object does not support deletion of attribute")
276+
"""Delete an attribute. This causes TypeError since deletion is prevented."""
277+
msg = "Card object does not support deletion of attribute"
278+
raise TypeError(msg)

python/phevaluator/evaluator.py

Lines changed: 14 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -1,33 +1,32 @@
11
"""Module evaluating cards."""
2-
from typing import Union
2+
3+
from __future__ import annotations
34

45
from .card import Card
56
from .hash import hash_quinary
6-
from .tables import (
7-
BINARIES_BY_ID,
8-
FLUSH,
9-
NO_FLUSH_5,
10-
NO_FLUSH_6,
11-
NO_FLUSH_7,
12-
SUITBIT_BY_ID,
13-
SUITS,
14-
)
7+
from .tables import BINARIES_BY_ID
8+
from .tables import FLUSH
9+
from .tables import NO_FLUSH_5
10+
from .tables import NO_FLUSH_6
11+
from .tables import NO_FLUSH_7
12+
from .tables import SUITBIT_BY_ID
13+
from .tables import SUITS
1514

1615
MIN_CARDS = 5
1716
MAX_CARDS = 7
1817

1918
NO_FLUSHES = {5: NO_FLUSH_5, 6: NO_FLUSH_6, 7: NO_FLUSH_7}
2019

2120

22-
def evaluate_cards(*cards: Union[int, str, Card]) -> int:
21+
def evaluate_cards(*cards: int | str | Card) -> int:
2322
"""Evaluate cards for the best five cards.
2423
2524
This function selects the best combination of the five cards from given cards and
2625
return its rank.
2726
The number of cards must be between 5 and 7.
2827
2928
Args:
30-
cards(Union[int, str, Card]): List of cards
29+
cards(int | str | Card): List of cards
3130
3231
Raises:
3332
ValueError: Unsupported size of the cards
@@ -39,17 +38,18 @@ def evaluate_cards(*cards: Union[int, str, Card]) -> int:
3938
>>> rank1 = evaluate_cards("Ac", "Ad", "Ah", "As", "Kc")
4039
>>> rank2 = evaluate_cards("Ac", "Ad", "Ah", "As", "Kd")
4140
>>> rank3 = evaluate_cards("Ac", "Ad", "Ah", "As", "Kc", "Qh")
42-
>>> rank1 == rank2 == rank3 # Those three are evaluated by `A A A A K`
41+
>>> rank1 == rank2 == rank3 # Those three are evaluated by `A A A A K`
4342
True
4443
"""
4544
int_cards = list(map(Card.to_id, cards))
4645
hand_size = len(cards)
4746

4847
if not (MIN_CARDS <= hand_size <= MAX_CARDS) or (hand_size not in NO_FLUSHES):
49-
raise ValueError(
48+
msg = (
5049
f"The number of cards must be between {MIN_CARDS} and {MAX_CARDS}."
5150
f"passed size: {hand_size}"
5251
)
52+
raise ValueError(msg)
5353

5454
return _evaluate_cards(*int_cards)
5555

0 commit comments

Comments
 (0)