Skip to content

Commit 728d492

Browse files
author
Chris Elion
authored
add pyupgrade to pre-commit and run (#4239)
1 parent 6dc68df commit 728d492

30 files changed

+49
-45
lines changed

.pre-commit-config.yaml

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -39,6 +39,13 @@ repos:
3939
# flake8-tidy-imports is used for banned-modules, not actually tidying
4040
additional_dependencies: [flake8-comprehensions==3.2.2, flake8-tidy-imports==4.1.0, flake8-bugbear==20.1.4]
4141

42+
- repo: https://github.com/asottile/pyupgrade
43+
rev: v2.7.0
44+
hooks:
45+
- id: pyupgrade
46+
args: [--py3-plus]
47+
exclude: .*barracuda.py
48+
4249
- repo: https://github.com/pre-commit/pre-commit-hooks
4350
rev: v2.5.0
4451
hooks:

gym-unity/setup.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,7 @@ def run(self):
2323
tag = os.getenv("CIRCLE_TAG")
2424

2525
if tag != EXPECTED_TAG:
26-
info = "Git tag: {0} does not match the expected tag of this app: {1}".format(
26+
info = "Git tag: {} does not match the expected tag of this app: {}".format(
2727
tag, EXPECTED_TAG
2828
)
2929
sys.exit(info)

ml-agents-envs/mlagents_envs/communicator.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@
33
from mlagents_envs.communicator_objects.unity_input_pb2 import UnityInputProto
44

55

6-
class Communicator(object):
6+
class Communicator:
77
def __init__(self, worker_id=0, base_port=5005):
88
"""
99
Python side of the communication. Must be used in pair with the right Unity Communicator equivalent.

ml-agents-envs/mlagents_envs/communicator_objects/unity_to_external_pb2_grpc.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@
44
from mlagents_envs.communicator_objects import unity_message_pb2 as mlagents__envs_dot_communicator__objects_dot_unity__message__pb2
55

66

7-
class UnityToExternalProtoStub(object):
7+
class UnityToExternalProtoStub:
88
# missing associated documentation comment in .proto file
99
pass
1010

@@ -21,7 +21,7 @@ def __init__(self, channel):
2121
)
2222

2323

24-
class UnityToExternalProtoServicer(object):
24+
class UnityToExternalProtoServicer:
2525
# missing associated documentation comment in .proto file
2626
pass
2727

ml-agents-envs/mlagents_envs/environment.py

Lines changed: 8 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -326,8 +326,8 @@ def behavior_specs(self) -> MappingType[str, BehaviorSpec]:
326326
def _assert_behavior_exists(self, behavior_name: str) -> None:
327327
if behavior_name not in self._env_specs:
328328
raise UnityActionException(
329-
"The group {0} does not correspond to an existing agent group "
330-
"in the environment".format(behavior_name)
329+
f"The group {behavior_name} does not correspond to an existing "
330+
f"agent group in the environment"
331331
)
332332

333333
def set_actions(self, behavior_name: BehaviorName, action: np.ndarray) -> None:
@@ -339,9 +339,9 @@ def set_actions(self, behavior_name: BehaviorName, action: np.ndarray) -> None:
339339
expected_shape = (len(self._env_state[behavior_name][0]), spec.action_size)
340340
if action.shape != expected_shape:
341341
raise UnityActionException(
342-
"The behavior {0} needs an input of dimension {1} for "
343-
"(<number of agents>, <action size>) but received input of "
344-
"dimension {2}".format(behavior_name, expected_shape, action.shape)
342+
f"The behavior {behavior_name} needs an input of dimension "
343+
f"{expected_shape} for (<number of agents>, <action size>) but "
344+
f"received input of dimension {action.shape}"
345345
)
346346
if action.dtype != expected_type:
347347
action = action.astype(expected_type)
@@ -357,10 +357,9 @@ def set_action_for_agent(
357357
expected_shape = (spec.action_size,)
358358
if action.shape != expected_shape:
359359
raise UnityActionException(
360-
f"The Agent {0} with BehaviorName {1} needs an input of dimension "
361-
f"{2} but received input of dimension {3}".format(
362-
agent_id, behavior_name, expected_shape, action.shape
363-
)
360+
f"The Agent {agent_id} with BehaviorName {behavior_name} needs "
361+
f"an input of dimension {expected_shape} but received input of "
362+
f"dimension {action.shape}"
364363
)
365364
expected_type = np.float32 if spec.is_action_continuous() else np.int32
366365
if action.dtype != expected_type:

ml-agents-envs/mlagents_envs/exception.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -75,4 +75,4 @@ class UnityWorkerInUseException(UnityException):
7575

7676
def __init__(self, worker_id):
7777
message = self.MESSAGE_TEMPLATE.format(str(worker_id))
78-
super(UnityWorkerInUseException, self).__init__(message)
78+
super().__init__(message)

ml-agents-envs/mlagents_envs/rpc_communicator.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -81,7 +81,7 @@ def check_port(self, port):
8181
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
8282
try:
8383
s.bind(("localhost", port))
84-
except socket.error:
84+
except OSError:
8585
raise UnityWorkerInUseException(self.worker_id)
8686
finally:
8787
s.close()

ml-agents-envs/mlagents_envs/side_channel/environment_parameters_channel.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,7 @@ class SamplerTypes(IntEnum):
2222
MULTIRANGEUNIFORM = 2
2323

2424
def __init__(self) -> None:
25-
channel_id = uuid.UUID(("534c891e-810f-11ea-a9d0-822485860400"))
25+
channel_id = uuid.UUID("534c891e-810f-11ea-a9d0-822485860400")
2626
super().__init__(channel_id)
2727

2828
def on_message_received(self, msg: IncomingMessage) -> None:

ml-agents-envs/mlagents_envs/side_channel/float_properties_channel.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@ class FloatPropertiesChannel(SideChannel):
1313
def __init__(self, channel_id: uuid.UUID = None) -> None:
1414
self._float_properties: Dict[str, float] = {}
1515
if channel_id is None:
16-
channel_id = uuid.UUID(("60ccf7d0-4f7e-11ea-b238-784f4387d1f7"))
16+
channel_id = uuid.UUID("60ccf7d0-4f7e-11ea-b238-784f4387d1f7")
1717
super().__init__(channel_id)
1818

1919
def on_message_received(self, msg: IncomingMessage) -> None:

ml-agents-envs/mlagents_envs/side_channel/side_channel_manager.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -33,7 +33,7 @@ def process_side_channel_message(self, data: bytes) -> None:
3333
)
3434
if len(message_data) != message_len:
3535
raise UnityEnvironmentException(
36-
"The message received by the side channel {0} was "
36+
"The message received by the side channel {} was "
3737
"unexpectedly short. Make sure your Unity Environment "
3838
"sending side channel data properly.".format(channel_id)
3939
)

ml-agents-envs/mlagents_envs/tests/test_side_channel.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -84,8 +84,8 @@ def test_raw_bytes():
8484
sender = RawBytesChannel(guid)
8585
receiver = RawBytesChannel(guid)
8686

87-
sender.send_raw_data("foo".encode("ascii"))
88-
sender.send_raw_data("bar".encode("ascii"))
87+
sender.send_raw_data(b"foo")
88+
sender.send_raw_data(b"bar")
8989

9090
data = SideChannelManager([sender]).generate_side_channel_messages()
9191
SideChannelManager([receiver]).process_side_channel_message(data)

ml-agents-envs/setup.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,7 @@ def run(self):
2323
tag = os.getenv("CIRCLE_TAG")
2424

2525
if tag != EXPECTED_TAG:
26-
info = "Git tag: {0} does not match the expected tag of this app: {1}".format(
26+
info = "Git tag: {} does not match the expected tag of this app: {}".format(
2727
tag, EXPECTED_TAG
2828
)
2929
sys.exit(info)

ml-agents/mlagents/trainers/buffer.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -134,7 +134,7 @@ def __init__(self):
134134
super().__init__()
135135

136136
def __str__(self):
137-
return ", ".join(["'{0}' : {1}".format(k, str(self[k])) for k in self.keys()])
137+
return ", ".join(["'{}' : {}".format(k, str(self[k])) for k in self.keys()])
138138

139139
def reset_agent(self) -> None:
140140
"""
@@ -275,7 +275,7 @@ def resequence_and_append(
275275
key_list = list(self.keys())
276276
if not self.check_length(key_list):
277277
raise BufferException(
278-
"The length of the fields {0} were not of same length".format(key_list)
278+
"The length of the fields {} were not of same length".format(key_list)
279279
)
280280
for field_key in key_list:
281281
target_buffer[field_key].extend(

ml-agents/mlagents/trainers/cli_utils.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -232,7 +232,7 @@ def load_config(config_path: str) -> Dict[str, Any]:
232232
try:
233233
with open(config_path) as data_file:
234234
return _load_config(data_file)
235-
except IOError:
235+
except OSError:
236236
abs_path = os.path.abspath(config_path)
237237
raise TrainerConfigError(f"Config file could not be found at {abs_path}.")
238238
except UnicodeDecodeError:

ml-agents/mlagents/trainers/components/bc/model.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@
33
from mlagents.trainers.policy.tf_policy import TFPolicy
44

55

6-
class BCModel(object):
6+
class BCModel:
77
def __init__(
88
self, policy: TFPolicy, learning_rate: float = 3e-4, anneal_steps: int = 0
99
):

ml-agents/mlagents/trainers/components/reward_signals/curiosity/model.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@
55
from mlagents.trainers.policy.tf_policy import TFPolicy
66

77

8-
class CuriosityModel(object):
8+
class CuriosityModel:
99
def __init__(
1010
self, policy: TFPolicy, encoding_size: int = 128, learning_rate: float = 3e-4
1111
):

ml-agents/mlagents/trainers/components/reward_signals/gail/model.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@
88
EPSILON = 1e-7
99

1010

11-
class GAILModel(object):
11+
class GAILModel:
1212
def __init__(
1313
self,
1414
policy: TFPolicy,

ml-agents/mlagents/trainers/components/reward_signals/reward_signal_factory.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -31,7 +31,7 @@ def create_reward_signal(
3131
"""
3232
rcls = NAME_TO_CLASS.get(name)
3333
if not rcls:
34-
raise UnityTrainerException("Unknown reward signal type {0}".format(name))
34+
raise UnityTrainerException("Unknown reward signal type {}".format(name))
3535

3636
class_inst = rcls(policy, settings)
3737
return class_inst

ml-agents/mlagents/trainers/ghost/trainer.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -58,7 +58,7 @@ def __init__(
5858
:param artifact_path: Path to store artifacts from this trainer.
5959
"""
6060

61-
super(GhostTrainer, self).__init__(
61+
super().__init__(
6262
brain_name, trainer_settings, training, artifact_path, reward_buff_cap
6363
)
6464

ml-agents/mlagents/trainers/policy/tf_policy.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -158,7 +158,7 @@ def _load_graph(self, model_path: str, reset_global_steps: bool = False) -> None
158158
ckpt = tf.train.get_checkpoint_state(model_path)
159159
if ckpt is None:
160160
raise UnityPolicyException(
161-
"The model {0} could not be loaded. Make "
161+
"The model {} could not be loaded. Make "
162162
"sure you specified the right "
163163
"--run-id and that the previous run you are loading from had the same "
164164
"behavior names.".format(model_path)
@@ -167,7 +167,7 @@ def _load_graph(self, model_path: str, reset_global_steps: bool = False) -> None
167167
self.saver.restore(self.sess, ckpt.model_checkpoint_path)
168168
except tf.errors.NotFoundError:
169169
raise UnityPolicyException(
170-
"The model {0} was found but could not be loaded. Make "
170+
"The model {} was found but could not be loaded. Make "
171171
"sure the model is from the same version of ML-Agents, has the same behavior parameters, "
172172
"and is using the same trainer configuration as the current run.".format(
173173
model_path

ml-agents/mlagents/trainers/ppo/trainer.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -44,7 +44,7 @@ def __init__(
4444
:param seed: The seed the model will be initialized with
4545
:param artifact_path: The directory within which to store artifacts from this trainer.
4646
"""
47-
super(PPOTrainer, self).__init__(
47+
super().__init__(
4848
brain_name, trainer_settings, training, artifact_path, reward_buff_cap
4949
)
5050
self.hyperparameters: PPOSettings = cast(

ml-agents/mlagents/trainers/stats.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -127,7 +127,7 @@ def add_property(
127127
) -> None:
128128
if property_type == StatsPropertyType.HYPERPARAMETERS:
129129
logger.info(
130-
"""Hyperparameters for behavior name {0}: \n{1}""".format(
130+
"""Hyperparameters for behavior name {}: \n{}""".format(
131131
category, self._dict_to_str(value, 0)
132132
)
133133
)
@@ -150,7 +150,7 @@ def _dict_to_str(self, param_dict: Dict[str, Any], num_tabs: int) -> str:
150150
[
151151
"\t"
152152
+ " " * num_tabs
153-
+ "{0}:\t{1}".format(
153+
+ "{}:\t{}".format(
154154
x, self._dict_to_str(param_dict[x], num_tabs + 1)
155155
)
156156
for x in param_dict
@@ -226,7 +226,7 @@ def _dict_to_tensorboard(self, name: str, input_dict: Dict[str, Any]) -> str:
226226
s_op = tf.summary.text(
227227
name,
228228
tf.convert_to_tensor(
229-
([[str(x), str(input_dict[x])] for x in input_dict])
229+
[[str(x), str(input_dict[x])] for x in input_dict]
230230
),
231231
)
232232
s = sess.run(s_op)

ml-agents/mlagents/trainers/tests/test_training_status.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,7 @@ def test_globaltrainingstatus(tmpdir):
2020
GlobalTrainingStatus.set_parameter_state("Category1", StatusType.LESSON_NUM, 3)
2121
GlobalTrainingStatus.save_state(path_dir)
2222

23-
with open(path_dir, "r") as fp:
23+
with open(path_dir) as fp:
2424
test_json = json.load(fp)
2525

2626
assert "Category1" in test_json

ml-agents/mlagents/trainers/trainer/rl_trainer.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -32,7 +32,7 @@ class RLTrainer(Trainer): # pylint: disable=abstract-method
3232
"""
3333

3434
def __init__(self, *args, **kwargs):
35-
super(RLTrainer, self).__init__(*args, **kwargs)
35+
super().__init__(*args, **kwargs)
3636
# collected_rewards is a dictionary from name of reward signal to a dictionary of agent_id to cumulative reward
3737
# used for reporting only. We always want to report the environment reward to Tensorboard, regardless
3838
# of what reward signals are actually present.

ml-agents/mlagents/trainers/trainer_controller.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -30,7 +30,7 @@
3030
from mlagents.trainers.agent_processor import AgentManager
3131

3232

33-
class TrainerController(object):
33+
class TrainerController:
3434
def __init__(
3535
self,
3636
trainer_factory: TrainerFactory,

ml-agents/mlagents/trainers/training_status.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -67,7 +67,7 @@ def load_state(path: str) -> None:
6767
:param path: Path to the JSON file containing the state.
6868
"""
6969
try:
70-
with open(path, "r") as f:
70+
with open(path) as f:
7171
loaded_dict = json.load(f)
7272
# Compare the metadata
7373
_metadata = loaded_dict[StatusType.STATS_METADATA.value]

ml-agents/setup.py

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,3 @@
1-
from io import open
21
import os
32
import sys
43

@@ -25,7 +24,7 @@ def run(self):
2524
tag = os.getenv("CIRCLE_TAG")
2625

2726
if tag != EXPECTED_TAG:
28-
info = "Git tag: {0} does not match the expected tag of this app: {1}".format(
27+
info = "Git tag: {} does not match the expected tag of this app: {}".format(
2928
tag, EXPECTED_TAG
3029
)
3130
sys.exit(info)

ml-agents/tests/yamato/check_coverage_percent.py

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

utils/validate_release_links.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -77,7 +77,7 @@ def check_file(filename: str, global_allow_pattern: Pattern) -> List[str]:
7777
Validate a single file and return any offending lines.
7878
"""
7979
bad_lines = []
80-
with open(filename, "r") as f:
80+
with open(filename) as f:
8181
for line in f:
8282
if not RELEASE_PATTERN.search(line):
8383
continue

utils/validate_versions.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -94,7 +94,7 @@ def set_version(
9494

9595

9696
def set_package_version(new_version: str) -> None:
97-
with open(MLAGENTS_PACKAGE_JSON_PATH, "r") as f:
97+
with open(MLAGENTS_PACKAGE_JSON_PATH) as f:
9898
package_json = json.load(f)
9999
if "version" in package_json:
100100
package_json["version"] = new_version
@@ -104,7 +104,7 @@ def set_package_version(new_version: str) -> None:
104104

105105

106106
def set_extension_package_version(new_version: str) -> None:
107-
with open(MLAGENTS_EXTENSIONS_PACKAGE_JSON_PATH, "r") as f:
107+
with open(MLAGENTS_EXTENSIONS_PACKAGE_JSON_PATH) as f:
108108
package_json = json.load(f)
109109
package_json["dependencies"]["com.unity.ml-agents"] = new_version
110110
with open(MLAGENTS_EXTENSIONS_PACKAGE_JSON_PATH, "w") as f:

0 commit comments

Comments
 (0)