Skip to content

Commit 0fa8fe3

Browse files
rkty13drvinceknight
authored andcommitted
Dropping support for Python 2 (#818)
* Removed floating point division workaround for Python 2.7. * Removed absolute_import future import. * Removed check for Python 2.x in import. * Removed floating point division workaround for Python 2. * Removed floating point division workaround for Python 2. * Removed floating point division workaround for Python 2. * Removed use of 0.0 for floating point division for Python 2. * Removed Python 2 unicode strings in top level files. * Removed Python 2 unicode strings from unit tests. * Removed Python 2 unicode strings from docs. * Removed Python 2 future division import. * Removed float casting in division. * Removed float casting for division. * Changed all calls to superclass methods to preferred zero argument Python 3 format. * Changed all calls to superclass methods in strategies to preferred zero argument Python 3 format. * Removed for floating point workarounds for Python 2. * Removed import check for Python 2 version of MagicMock. * Removed direct reference to Player and changed to super().
1 parent 2a83208 commit 0fa8fe3

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

54 files changed

+313
-348
lines changed

axelrod/__init__.py

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,3 @@
1-
from __future__ import absolute_import
21
import os
32

43
on_windows = os.name == 'nt'

axelrod/deterministic_cache.py

Lines changed: 6 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,4 @@
1-
try:
2-
# Python 2.x
3-
from UserDict import UserDict
4-
except ImportError:
5-
# Python 3.x
6-
from collections import UserDict
1+
from collections import UserDict
72
import pickle
83

94
from axelrod import Player
@@ -41,7 +36,7 @@ def __init__(self, file_name=None):
4136
file_name : string
4237
Path to a previously saved cache file
4338
"""
44-
UserDict.__init__(self)
39+
super().__init__()
4540
self.mutable = True
4641
if file_name is not None:
4742
self.load(file_name)
@@ -56,13 +51,13 @@ def _key_transform(self, key):
5651
return key[0].name, key[1].name, key[2]
5752

5853
def __delitem__(self, key):
59-
return UserDict.__delitem__(self, self._key_transform(key))
54+
return super().__delitem__(self._key_transform(key))
6055

6156
def __getitem__(self, key):
62-
return UserDict.__getitem__(self, self._key_transform(key))
57+
return super().__getitem__(self._key_transform(key))
6358

6459
def __contains__(self, key):
65-
return UserDict.__contains__(self, self._key_transform(key))
60+
return super().__contains__(self._key_transform(key))
6661

6762
def __setitem__(self, key, value):
6863
"""Overrides the UserDict.__setitem__ method in order to validate
@@ -78,7 +73,7 @@ def __setitem__(self, key, value):
7873
raise ValueError(
7974
'Value must be a list with length equal to turns attribute')
8075

81-
UserDict.__setitem__(self, self._key_transform(key), value)
76+
super().__setitem__(self._key_transform(key), value)
8277

8378
def _is_valid_key(self, key):
8479
"""Validate a proposed dictionary key

axelrod/ecosystem.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -24,10 +24,10 @@ def __init__(self, results, fitness=None, population=None):
2424
elif len(population) != self.nplayers:
2525
raise TypeError("Population vector must be same size as number of players")
2626
else:
27-
norm = float(sum(population))
27+
norm = sum(population)
2828
self.population_sizes = [[p / norm for p in population]]
2929
else:
30-
self.population_sizes = [[1.0 / self.nplayers for i in range(self.nplayers)]]
30+
self.population_sizes = [[1 / self.nplayers for i in range(self.nplayers)]]
3131

3232
# This function is quite arbitrary and probably only influences the
3333
# kinetics for the current code.

axelrod/interaction_utils.py

Lines changed: 7 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -46,7 +46,7 @@ def compute_final_score_per_turn(interactions, game=None):
4646
return None
4747

4848
final_score_per_turn = tuple(
49-
sum([score[player_index] for score in scores]) / (float(num_turns))
49+
sum([score[player_index] for score in scores]) / num_turns
5050
for player_index in [0, 1])
5151
return final_score_per_turn
5252

@@ -83,7 +83,7 @@ def compute_normalised_cooperation(interactions):
8383
num_turns = len(interactions)
8484
cooperation = compute_cooperations(interactions)
8585

86-
normalised_cooperation = tuple([c / float(num_turns) for c in cooperation])
86+
normalised_cooperation = tuple([c / num_turns for c in cooperation])
8787

8888
return normalised_cooperation
8989

@@ -129,30 +129,27 @@ def compute_normalised_state_distribution(interactions):
129129
return None
130130

131131
interactions_count = Counter(interactions)
132-
total = sum(interactions_count.values(), 0.0)
133-
# By starting the sum with 0.0 we make sure total is a floating point value,
134-
# avoiding the Python 2 floor division behaviour of / with integer operands
135-
# (Stack Overflow)
132+
total = sum(interactions_count.values(), 0)
136133

137134
normalized_count = Counter({key: value / total for key, value in
138135
interactions_count.items()})
139136
return normalized_count
140137

141138

142-
def sparkline(actions, c_symbol=u'█', d_symbol=u' '):
143-
return u''.join([
139+
def sparkline(actions, c_symbol='█', d_symbol=' '):
140+
return ''.join([
144141
c_symbol if play == 'C' else d_symbol for play in actions])
145142

146143

147-
def compute_sparklines(interactions, c_symbol=u'█', d_symbol=u' '):
144+
def compute_sparklines(interactions, c_symbol='█', d_symbol=' '):
148145
"""Returns the sparklines for a set of interactions"""
149146
if len(interactions) == 0:
150147
return None
151148

152149
histories = list(zip(*interactions))
153150
return (
154151
sparkline(histories[0], c_symbol, d_symbol) +
155-
u'\n' +
152+
'\n' +
156153
sparkline(histories[1], c_symbol, d_symbol))
157154

158155

axelrod/match.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -171,7 +171,7 @@ def normalised_state_distribution(self):
171171
"""
172172
return iu.compute_normalised_state_distribution(self.result)
173173

174-
def sparklines(self, c_symbol=u'█', d_symbol=u' '):
174+
def sparklines(self, c_symbol='█', d_symbol=' '):
175175
return iu.compute_sparklines(self.result, c_symbol, d_symbol)
176176

177177
def __len__(self):

axelrod/match_generator.py

Lines changed: 3 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,3 @@
1-
from __future__ import division
21
from math import ceil, log
32
import random
43

@@ -113,7 +112,7 @@ def __init__(self, players, prob_end, game, repetitions, noise=0):
113112
noise : float, 0
114113
The probability that a player's intended action should be flipped
115114
"""
116-
super(ProbEndRoundRobinMatches, self).__init__(
115+
super().__init__(
117116
players, turns=float("inf"), game=game, repetitions=repetitions,
118117
noise=noise)
119118
self.prob_end = prob_end
@@ -165,7 +164,7 @@ def sample_length(self):
165164

166165
def estimated_size(self):
167166
"""Rough estimate of the number of matches that will be generated."""
168-
size = self.__len__() * (1. / self.prob_end) * self.repetitions
167+
size = self.__len__() * (1 / self.prob_end) * self.repetitions
169168
return size
170169

171170

@@ -221,8 +220,7 @@ def __init__(self, players, turns, game, repetitions, edges, noise=0):
221220
if not graph_is_connected(edges, players):
222221
raise ValueError("The graph edges do not include all players.")
223222
self.edges = edges
224-
super(SpatialMatches, self).__init__(players, turns, game, repetitions,
225-
noise)
223+
super().__init__(players, turns, game, repetitions, noise)
226224

227225
def build_match_chunks(self):
228226
for edge in self.edges:

axelrod/mock_player.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@ class MockPlayer(Player):
1212
def __init__(self, player, move):
1313
# Need to retain history for opponents that examine opponents history
1414
# Do a deep copy just to be safe
15-
Player.__init__(self)
15+
super().__init__()
1616
self.history = copy.deepcopy(player.history)
1717
self.cooperations = player.cooperations
1818
self.defections = player.defections

axelrod/moran.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -304,7 +304,7 @@ def __init__(self, players, interaction_graph, reproduction_graph=None,
304304
match_class: subclass of Match
305305
The match type to use for scoring
306306
"""
307-
MoranProcess.__init__(self, players, turns=turns, noise=noise,
307+
super().__init__(players, turns=turns, noise=noise,
308308
deterministic_cache=deterministic_cache,
309309
mutation_rate=mutation_rate, mode=mode)
310310
if not reproduction_graph:

axelrod/plot.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -233,7 +233,7 @@ def stackplot(self, eco, title=None, logscale=True, ax=None):
233233
ticks = []
234234
for i, n in enumerate(self.result_set.ranked_names):
235235
x = -0.01
236-
y = (i + 0.5) * 1.0 / self.result_set.nplayers
236+
y = (i + 0.5) * 1 / self.result_set.nplayers
237237
ax.annotate(n, xy=(x, y), xycoords=trans, clip_on=False,
238238
va='center', ha='right', fontsize=5)
239239
ticks.append(y)

axelrod/result_set.py

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -200,7 +200,7 @@ def _build_cooperating_rating(self):
200200
enumerate(total_length_v_opponent)]
201201

202202
# Max is to deal with edge cases of matches that have no turns
203-
return [sum(cs) / max(1, float(sum(ls))) for cs, ls
203+
return [sum(cs) / max(1, sum(ls)) for cs, ls
204204
in zip(self.cooperation, lengths)]
205205

206206
@update_progress_bar
@@ -354,7 +354,7 @@ def _build_normalised_state_distribution(self):
354354
counters = []
355355
for counter in player:
356356
total = sum(counter.values())
357-
counters.append(Counter({key: float(value) / total for
357+
counters.append(Counter({key: value / total for
358358
key, value in counter.items()}))
359359
norm.append(counters)
360360
return norm
@@ -622,7 +622,7 @@ def _build_good_partner_rating(self):
622622
attribute
623623
"""
624624
return [sum(self.good_partner_matrix[player]) /
625-
max(1, float(self.total_interactions[player]))
625+
max(1, self.total_interactions[player])
626626
for player in range(self.nplayers)]
627627

628628
@update_progress_bar
@@ -632,7 +632,7 @@ def _build_initial_cooperation_rate(self):
632632
cooperation rate attribute
633633
"""
634634
return [self.initial_cooperation_count[player] /
635-
max(1, float(self.total_interactions[player]))
635+
max(1, self.total_interactions[player])
636636
for player in range(self.nplayers)]
637637

638638
def _build_score_related_metrics(self, progress_bar=False,
@@ -783,7 +783,7 @@ def summarise(self):
783783
p = sum([opp[state] for j, opp in enumerate(player) if i != j])
784784
counts.append(p)
785785
try:
786-
counts = [float(c) / sum(counts) for c in counts]
786+
counts = [c / sum(counts) for c in counts]
787787
except ZeroDivisionError:
788788
counts = [0 for c in counts]
789789
state_prob.append(counts)

axelrod/strategies/_strategies.py

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,3 @@
1-
from __future__ import absolute_import
2-
31
from .alternator import Alternator
42
from .adaptive import Adaptive
53
from .ann import EvolvedANN, EvolvedANN5, EvolvedANNNoise05

axelrod/strategies/adaptive.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -26,7 +26,7 @@ class Adaptive(Player):
2626

2727
@init_args
2828
def __init__(self, initial_plays=None):
29-
Player.__init__(self)
29+
super().__init__()
3030
if not initial_plays:
3131
initial_plays = [C] * 6 + [D] * 5
3232
self.initial_plays = initial_plays
@@ -53,5 +53,5 @@ def strategy(self, opponent):
5353
return D
5454

5555
def reset(self):
56-
Player.reset(self)
56+
super().reset()
5757
self.scores = {C: 0, D: 0}

axelrod/strategies/ann.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -64,7 +64,7 @@ class ANN(Player):
6464

6565
@init_args
6666
def __init__(self, weights, num_features, num_hidden):
67-
Player.__init__(self)
67+
super().__init__()
6868
(i2h, h2o, bias) = split_weights(weights, num_features, num_hidden)
6969
self.input_to_hidden_layer_weights = i2h
7070
self.hidden_to_output_layer_weights = h2o
@@ -192,7 +192,7 @@ class EvolvedANN(ANN):
192192
@init_args
193193
def __init__(self):
194194
num_features, num_hidden, weights = nn_weights["Evolved ANN"]
195-
ANN.__init__(self, weights, num_features, num_hidden)
195+
super().__init__(weights, num_features, num_hidden)
196196

197197

198198
class EvolvedANN5(ANN):
@@ -210,7 +210,7 @@ class EvolvedANN5(ANN):
210210
@init_args
211211
def __init__(self):
212212
num_features, num_hidden, weights = nn_weights["Evolved ANN 5"]
213-
ANN.__init__(self, weights, num_features, num_hidden)
213+
super().__init__(weights, num_features, num_hidden)
214214

215215

216216
class EvolvedANNNoise05(ANN):
@@ -228,4 +228,4 @@ class EvolvedANNNoise05(ANN):
228228
@init_args
229229
def __init__(self):
230230
num_features, num_hidden, weights = nn_weights["Evolved ANN 5 Noise 05"]
231-
ANN.__init__(self, weights, num_features, num_hidden)
231+
super().__init__(weights, num_features, num_hidden)

axelrod/strategies/apavlov.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -26,7 +26,7 @@ class APavlov2006(Player):
2626
}
2727

2828
def __init__(self):
29-
Player.__init__(self)
29+
super().__init__()
3030
self.opponent_class = None
3131

3232
def strategy(self, opponent):
@@ -66,7 +66,7 @@ def strategy(self, opponent):
6666
return C
6767

6868
def reset(self):
69-
Player.reset(self)
69+
super().reset()
7070
self.opponent_class = None
7171

7272

@@ -93,7 +93,7 @@ class APavlov2011(Player):
9393
}
9494

9595
def __init__(self):
96-
Player.__init__(self)
96+
super().__init__()
9797
self.opponent_class = None
9898

9999
def strategy(self, opponent):
@@ -121,5 +121,5 @@ def strategy(self, opponent):
121121
return D if opponent.history[-1:] == [D] else C
122122

123123
def reset(self):
124-
Player.reset(self)
124+
super().reset()
125125
self.opponent_class = None

0 commit comments

Comments
 (0)