Skip to content

Commit 86fae94

Browse files
committed
Fix some type hints
1 parent 9f2e8a6 commit 86fae94

File tree

4 files changed

+32
-26
lines changed

4 files changed

+32
-26
lines changed

axelrod/evolvable_player.py

Lines changed: 10 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
from pickle import dumps, loads
22
from random import randrange
3+
from typing import Dict, List
34
from .player import Player
45

56

@@ -17,14 +18,14 @@ class EvolvablePlayer(Player):
1718

1819
name = "EvolvablePlayer"
1920
parent_class = Player
20-
parent_kwargs = []
21+
parent_kwargs = [] # type: List[str]
2122

2223
def overwrite_init_kwargs(self, **kwargs):
2324
"""Use to overwrite parameters for proper cloning and testing."""
2425
for k, v in kwargs.items():
2526
self.init_kwargs[k] = v
2627

27-
def create_new(self, **kwargs):
28+
def create_new(self, **kwargs) -> EvolvablePlayer:
2829
"""Creates a new variant with parameters overwritten by kwargs."""
2930
init_kwargs = self.init_kwargs.copy()
3031
init_kwargs.update(kwargs)
@@ -34,22 +35,22 @@ def create_new(self, **kwargs):
3435
# but you must overwrite both.
3536

3637
def serialize_parameters(self):
37-
"""Serialize parameters to a string for reinforcement learning."""
38+
"""Serialize parameters."""
3839
return dumps(self.init_kwargs)
3940

4041
@classmethod
41-
def deserialize_parameters(cls, serialized):
42+
def deserialize_parameters(cls, serialized) -> EvolvablePlayer:
4243
"""Deserialize parameters to a Player instance."""
4344
init_kwargs = loads(serialized)
4445
return cls(**init_kwargs)
4546

4647
# Optional methods for evolutionary algorithms and Moran processes.
4748

48-
def mutate(self):
49+
def mutate(self) -> EvolvablePlayer:
4950
"""Optional method to allow Player to produce a variant (not in place)."""
5051
pass
5152

52-
def crossover(self, other):
53+
def crossover(self, other) -> EvolvablePlayer:
5354
"""Optional method to allow Player to produce variants in combination with another player. Returns a new
5455
Player."""
5556
pass
@@ -65,17 +66,17 @@ def create_vector_bounds(self):
6566
pass
6667

6768

68-
def copy_lists(lists):
69+
def copy_lists(lists: List[List]) -> List[List]:
6970
return list(map(list, lists))
7071

7172

72-
def crossover_lists(list1, list2):
73+
def crossover_lists(list1: List, list2: List) -> List:
7374
cross_point = randrange(len(list1))
7475
new_list = list(list1[:cross_point]) + list(list2[cross_point:])
7576
return new_list
7677

7778

78-
def crossover_dictionaries(table1, table2):
79+
def crossover_dictionaries(table1: Dict, table2: Dict) -> Dict:
7980
keys = list(table1.keys())
8081
cross_point = randrange(len(keys))
8182
new_items = [(k, table1[k]) for k in keys[:cross_point]]

axelrod/strategies/cycler.py

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
import copy
22
import itertools
33
import random
4+
from typing import List, Tuple
45

56
from axelrod.action import Action, actions_to_str, str_to_actions
67
from axelrod.evolvable_player import EvolvablePlayer, InsufficientParametersError, crossover_lists
@@ -38,7 +39,7 @@ def __init__(self) -> None:
3839
self.first_three = self._get_first_three()
3940

4041
@staticmethod
41-
def _get_first_three():
42+
def _get_first_three() -> List[Action]:
4243
return [C, D, D]
4344

4445
def strategy(self, opponent: Player) -> Action:
@@ -86,13 +87,12 @@ def __init__(self, cycle: str = "CCD") -> None:
8687
"""
8788
super().__init__()
8889
self.cycle = cycle
89-
self.cycle_iter = None
9090
self.set_cycle(cycle=cycle)
9191

9292
def strategy(self, opponent: Player) -> Action:
9393
return next(self.cycle_iter)
9494

95-
def set_cycle(self, cycle):
95+
def set_cycle(self, cycle: str):
9696
"""Set or change the cycle."""
9797
self.cycle = cycle
9898
self.cycle_iter = itertools.cycle(str_to_actions(self.cycle))
@@ -123,7 +123,7 @@ def __init__(
123123
self.mutation_potency = mutation_potency
124124

125125
@classmethod
126-
def _normalize_parameters(cls, cycle=None, cycle_length=None):
126+
def _normalize_parameters(cls, cycle=None, cycle_length=None) -> Tuple[str, int]:
127127
"""Compute other parameters from those that may be missing, to ensure proper cloning."""
128128
if not cycle:
129129
if not cycle_length:
@@ -133,13 +133,13 @@ def _normalize_parameters(cls, cycle=None, cycle_length=None):
133133
return cycle, cycle_length
134134

135135
@classmethod
136-
def _generate_random_cycle(cls, cycle_length):
136+
def _generate_random_cycle(cls, cycle_length: int) -> str:
137137
"""
138138
Generate a sequence of random moves
139139
"""
140140
return actions_to_str(random.choice(actions) for _ in range(cycle_length))
141141

142-
def mutate(self):
142+
def mutate(self) -> EvolvablePlayer:
143143
"""
144144
Basic mutation which may change any random actions in the sequence.
145145
"""
@@ -154,7 +154,7 @@ def mutate(self):
154154
cycle, _ = self._normalize_parameters(cycle)
155155
return self.create_new(cycle=cycle)
156156

157-
def crossover(self, other):
157+
def crossover(self, other) -> EvolvablePlayer:
158158
"""
159159
Creates and returns a new Player instance with a single crossover point.
160160
"""

axelrod/strategies/finite_state_machines.py

Lines changed: 14 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,15 @@
11
import itertools
22
from random import randrange
3+
from typing import Any, List, Sequence, Tuple, Union
34
import numpy.random as random
45
from numpy.random import choice
5-
from axelrod.action import Action, UnknownActionError
6+
from axelrod.action import Action
67
from axelrod.evolvable_player import EvolvablePlayer, InsufficientParametersError, copy_lists
78
from axelrod.player import Player
89

910
C, D = Action.C, Action.D
1011
actions = (C, D)
12+
Transition = Tuple[int, Action, int, Action]
1113

1214

1315
class SimpleFSM(object):
@@ -107,7 +109,7 @@ class FSMPlayer(Player):
107109

108110
def __init__(
109111
self,
110-
transitions: tuple = ((1, C, 1, C), (1, D, 1, D)),
112+
transitions: Tuple[Transition, ...] = ((1, C, 1, C), (1, D, 1, D)),
111113
initial_state: int = 1,
112114
initial_action: Action = C
113115
) -> None:
@@ -164,38 +166,40 @@ def __init__(
164166
num_states=self.num_states)
165167

166168
@classmethod
167-
def normalize_transitions(cls, transitions):
168-
"""Translate List[List] to Tuple[Tuple]"""
169+
def normalize_transitions(cls, transitions: Sequence[Sequence]) -> Tuple[Tuple[Any, ...], ...]:
170+
"""Translate a list of lists to a tuple of tuples."""
169171
normalized = []
170172
for t in transitions:
171173
normalized.append(tuple(t))
172174
return tuple(normalized)
173175

174176
@classmethod
175-
def _normalize_parameters(cls, transitions=None, initial_state=None, initial_action=None, num_states=None):
177+
def _normalize_parameters(cls, transitions: Tuple = None, initial_state: int = None, initial_action: Action = None,
178+
num_states: int = None) -> Tuple[Tuple, int, Action, int]:
176179
if not ((transitions is not None) and (initial_state is not None) and (initial_action is not None)):
177180
if not num_states:
178181
raise InsufficientParametersError("Insufficient Parameters to instantiate EvolvableFSMPlayer")
179182
transitions, initial_state, initial_action = cls.random_params(num_states)
180183
transitions = cls.normalize_transitions(transitions)
184+
num_states = len(transitions) // 2
181185
return transitions, initial_state, initial_action, num_states
182186

183187
@property
184-
def num_states(self):
188+
def num_states(self) -> int:
185189
return self.fsm.num_states()
186190

187191
@classmethod
188-
def random_params(cls, num_states):
192+
def random_params(cls, num_states: int) -> Tuple[Tuple[Transition, ...], int, Action]:
189193
rows = []
190194
for j in range(num_states):
191195
for action in actions:
192196
next_state = randrange(num_states)
193197
next_action = choice(actions)
194-
row = [j, action, next_state, next_action]
195-
rows.append(tuple(row))
198+
row = (j, action, next_state, next_action)
199+
rows.append(row)
196200
initial_state = randrange(num_states)
197201
initial_action = choice(actions)
198-
return rows, initial_state, initial_action
202+
return tuple(rows), initial_state, initial_action
199203

200204
@staticmethod
201205
def mutate_rows(rows, mutation_probability):

run_mypy.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66
"axelrod/action.py",
77
"axelrod/deterministic_cache.py",
88
"axelrod/ecosystem.py",
9+
"axelrod/evolvable_player.py",
910
"axelrod/fingerprint.py",
1011
"axelrod/game.py",
1112
"axelrod/load_data_.py",

0 commit comments

Comments
 (0)