Skip to content

Commit 46b8321

Browse files
skyline75489facebook-github-bot
authored andcommitted
Remove unused six code for Python 2/3 compatibility (pytorch#48077)
Summary: This is basically a reborn version of pytorch#45254 . Ref: pytorch#42919 Pull Request resolved: pytorch#48077 Reviewed By: ngimel Differential Revision: D25687042 Pulled By: bugra fbshipit-source-id: 05f20a6f3c5212f73d0b1505b493b720e6cf74e5
1 parent abacf27 commit 46b8321

25 files changed

+34
-64
lines changed

benchmarks/distributed/ddp/benchmark.py

-4
Original file line numberDiff line numberDiff line change
@@ -26,10 +26,6 @@
2626
import torchvision
2727

2828

29-
if not torch._six.PY3:
30-
raise RuntimeError("DDP benchmark requires Python 3")
31-
32-
3329
def allgather_object(obj):
3430
buffer = io.BytesIO()
3531
torch.save(obj, buffer)

benchmarks/distributed/ddp/diff.py

-4
Original file line numberDiff line numberDiff line change
@@ -9,10 +9,6 @@
99
import numpy as np
1010

1111

12-
if not torch._six.PY3:
13-
raise RuntimeError("DDP benchmark requires Python 3")
14-
15-
1612
def load(path):
1713
with open(path, 'r') as f:
1814
return json.load(f)

caffe2/contrib/tensorboard/tensorboard_exporter.py

+1-2
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,6 @@
77
import copy
88
import logging
99
import os
10-
import six
1110

1211
from caffe2.proto import caffe2_pb2
1312
from caffe2.python import core, workspace
@@ -93,7 +92,7 @@ def _get_blob_names(ops):
9392

9493

9594
def _remap_keys(m, f):
96-
m2 = {f(key): value for key, value in six.iteritems(m)}
95+
m2 = {f(key): value for key, value in m.items()}
9796
m.clear()
9897
m.update(m2)
9998

caffe2/python/context.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@
33

44
import inspect
55
import threading
6-
import six
6+
import functools
77

88

99
class _ContextInfo(object):
@@ -91,7 +91,7 @@ def __exit__(self, *args):
9191
_context_registry().get(cls).exit(self)
9292

9393
def __call__(self, func):
94-
@six.wraps(func)
94+
@functools.wraps(func)
9595
def wrapper(*args, **kwargs):
9696
with self:
9797
return func(*args, **kwargs)

caffe2/python/experiment_util.py

+1-2
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,6 @@
1010
import logging
1111
import socket
1212
import abc
13-
import six
1413

1514
from collections import OrderedDict
1615
from future.utils import viewkeys, viewvalues
@@ -26,7 +25,7 @@
2625

2726

2827
class ExternalLogger(object):
29-
six.add_metaclass(abc.ABCMeta)
28+
__metaclass__ = abc.ABCMeta
3029

3130
@abc.abstractmethod
3231
def set_runtime_args(self, runtime_args):

caffe2/python/hypothesis_test_util.py

+2-3
Original file line numberDiff line numberDiff line change
@@ -50,7 +50,6 @@
5050
import logging
5151
import numpy as np
5252
import os
53-
import six
5453
import struct
5554

5655

@@ -748,5 +747,5 @@ def assertRunOpRaises(
748747
if regexp is None:
749748
self.assertRaises(exception, workspace.RunOperatorOnce, op)
750749
else:
751-
six.assertRaisesRegex(
752-
self, exception, regexp, workspace.RunOperatorOnce, op)
750+
self.assertRaisesRegex(
751+
exception, regexp, workspace.RunOperatorOnce, op)

caffe2/python/layer_model_helper.py

+4-5
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,6 @@
2222

2323
import logging
2424
import numpy as np
25-
import six
2625
import copy
2726
logger = logging.getLogger(__name__)
2827

@@ -125,7 +124,7 @@ def filter_metrics_schema(self, white_set):
125124

126125
def add_ad_hoc_plot_blob(self, blob, dtype=None):
127126
assert isinstance(
128-
blob, (six.string_types, core.BlobReference)
127+
blob, (str, core.BlobReference)
129128
), "expect type str or BlobReference, but got {}".format(type(blob))
130129
dtype = dtype or (np.float, (1, ))
131130
self.add_metric_field(str(blob), schema.Scalar(dtype, blob))
@@ -173,7 +172,7 @@ def initializer(blob_name):
173172
def add_global_constant(
174173
self, name, array=None, dtype=None, initializer=None
175174
):
176-
assert isinstance(name, six.string_types), (
175+
assert isinstance(name, str), (
177176
'name should be a string as we are using it as map key')
178177
# This is global namescope for constants. They will be created in all
179178
# init_nets and there should be very few of them.
@@ -310,7 +309,7 @@ def create_param(self, param_name, shape, initializer, optimizer=None,
310309
ps_param=None, regularizer=None):
311310
if isinstance(param_name, core.BlobReference):
312311
param_name = str(param_name)
313-
elif isinstance(param_name, six.string_types):
312+
elif isinstance(param_name, str):
314313
# Parameter name will be equal to current Namescope that got
315314
# resolved with the respect of parameter sharing of the scopes.
316315
param_name = parameter_sharing_context.get_parameter_name(
@@ -750,6 +749,6 @@ def breakdown_map(self, breakdown_map):
750749
# TODO(xlwang): provide more rich feature information in breakdown_map;
751750
# and change the assertion accordingly
752751
assert isinstance(breakdown_map, dict)
753-
assert all(isinstance(k, six.string_types) for k in breakdown_map)
752+
assert all(isinstance(k, str) for k in breakdown_map)
754753
assert sorted(breakdown_map.values()) == list(range(len(breakdown_map)))
755754
self._breakdown_map = breakdown_map

caffe2/python/layer_parameter_sharing_test.py

+1-2
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,6 @@
99
)
1010
from caffe2.python.optimizer import AdagradOptimizer, AdamOptimizer
1111
from caffe2.python.layer_test_util import LayersTestCase
12-
import six
1312

1413

1514
class ParameterSharingTest(LayersTestCase):
@@ -116,7 +115,7 @@ def test_layer_shared_parameter_name_different_shapes(self):
116115
self.assertEquals(self.model.layers[-1].w,
117116
'global_scope/fc/w')
118117

119-
with six.assertRaisesRegex(self, ValueError, 'Got inconsistent shapes .*'):
118+
with self.assertRaisesRegex(ValueError, 'Got inconsistent shapes .*'):
120119
self.model.FC(
121120
self.model.input_feature_schema.float_features,
122121
output_dims + 1

caffe2/python/layers/functional.py

+1-2
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,6 @@
1111
)
1212
import caffe2.proto.caffe2_pb2 as caffe2_pb2
1313
import numpy as np
14-
import six
1514
import logging
1615

1716
logger = logging.getLogger(__name__)
@@ -31,7 +30,7 @@ def __init__(self, model, input_record, output_names_or_num, function,
3130
self._kwargs = kwargs
3231
return_struct = (
3332
isinstance(output_names_or_num, list) or
34-
(isinstance(output_names_or_num, six.integer_types) and
33+
(isinstance(output_names_or_num, int) and
3534
output_names_or_num != 1)
3635
)
3736

caffe2/python/layers/sampling_trainable_mixin.py

+1-2
Original file line numberDiff line numberDiff line change
@@ -6,10 +6,9 @@
66

77

88
import abc
9-
import six
109

1110

12-
class SamplingTrainableMixin(six.with_metaclass(abc.ABCMeta, object)):
11+
class SamplingTrainableMixin(metaclass=abc.ABCMeta):
1312

1413
def __init__(self, *args, **kwargs):
1514
super(SamplingTrainableMixin, self).__init__(*args, **kwargs)

caffe2/python/layers/tags.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@
55

66

77

8-
import six
8+
import functools
99

1010
from caffe2.python import context
1111

@@ -104,7 +104,7 @@ def __exit__(self, type, value, traceback):
104104
TagContext.current().remove_tags(self.tags)
105105

106106
def __call__(self, func):
107-
@six.wraps(func)
107+
@functools.wraps(func)
108108
def wrapper(*args, **kwargs):
109109
with self:
110110
return func(*args, **kwargs)

caffe2/python/model_helper.py

+1-2
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,6 @@
2121
from itertools import chain
2222

2323
import logging
24-
import six
2524

2625

2726
# _known_working_ops are operators that do not need special care.
@@ -199,7 +198,7 @@ def create_param(self, param_name, shape, initializer, tags=None):
199198
# ParameterSharing will be applied.
200199
if isinstance(param_name, core.BlobReference):
201200
param_name = str(param_name)
202-
elif isinstance(param_name, six.string_types):
201+
elif isinstance(param_name, str):
203202
# Parameter name will be equal to current Namescope that got
204203
# resolved with the respect of parameter sharing of the scopes.
205204
param_name = parameter_sharing_context.get_parameter_name(

caffe2/python/modeling/initializers.py

+1-3
Original file line numberDiff line numberDiff line change
@@ -6,8 +6,6 @@
66
from caffe2.python.core import DataType, BlobReference, ScopedBlobReference
77
from caffe2.python.modeling.parameter_info import ParameterInfo
88

9-
import six
10-
119

1210
class Initializer(object):
1311
'''
@@ -47,7 +45,7 @@ class ExternalInitializer(object):
4745
def create_param(self, param_name, init_net, shape):
4846
if isinstance(param_name, BlobReference):
4947
param = BlobReference(str(param_name), init_net)
50-
elif isinstance(param_name, six.string_types):
48+
elif isinstance(param_name, str):
5149
param = ScopedBlobReference(param_name, init_net)
5250
else:
5351
raise TypeError("Unsupported type for param_name")

caffe2/python/modeling/net_modifier.py

+1-2
Original file line numberDiff line numberDiff line change
@@ -4,10 +4,9 @@
44

55

66
import abc
7-
import six
87

98

10-
class NetModifier(six.with_metaclass(abc.ABCMeta, object)):
9+
class NetModifier(metaclass=abc.ABCMeta):
1110
"""
1211
An abstraction class for supporting modifying a generated net.
1312
Inherited classes should implement the modify_net method where

caffe2/python/onnx/tests/c2_ref_test.py

+2-4
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,6 @@
88

99
import json
1010
import os
11-
import six
1211
import unittest
1312

1413
from caffe2.python import core
@@ -44,9 +43,8 @@ def test_check_arguments(self):
4443
b2.convert_node(node_def.SerializeToString())
4544

4645
bad_node_def = make_node("Add", inputs=["X", "Y"], outputs=["Z"], foo=42, bar=56)
47-
with six.assertRaisesRegex(self,
48-
RuntimeError,
49-
"Don't know how to map unexpected argument (foo|bar)"):
46+
with self.assertRaisesRegex(RuntimeError,
47+
"Don't know how to map unexpected argument (foo|bar)"):
5048
b2.convert_node(bad_node_def.SerializeToString())
5149

5250
def test_dynamicslice_3inputs_graph(self):

caffe2/python/onnx/tests/conversion_test.py

+3-4
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,6 @@
66

77

88
import json
9-
import six
109
import tempfile
1110
import textwrap
1211
import traceback
@@ -82,9 +81,9 @@ def test_caffe2_to_onnx_value_info(self):
8281
caffe2_net.flush()
8382

8483
args = [caffe2_net.name, '--output', output.name]
85-
six.assertRaisesRegex(self, Exception,
86-
'value info',
87-
self._run_command, caffe2_to_onnx, args)
84+
self.assertRaisesRegex(Exception,
85+
'value info',
86+
self._run_command, caffe2_to_onnx, args)
8887

8988
args.extend([
9089
'--value-info',

caffe2/python/operator_test/image_input_op_test.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@
1313
from PIL import Image
1414
import numpy as np
1515
import shutil
16-
import six
16+
import io
1717
import sys
1818
import tempfile
1919

@@ -134,7 +134,7 @@ def create_test(output_dir, width, height, default_bound, minsize, crop, means,
134134
img_array = np.random.random_integers(
135135
0, 255, [height, width, 3]).astype(np.uint8)
136136
img_obj = Image.fromarray(img_array)
137-
img_str = six.BytesIO()
137+
img_str = io.BytesIO()
138138
img_obj.save(img_str, 'PNG')
139139

140140
# Create a random bounding box for every other image

caffe2/python/operator_test/reshape_ops_test.py

-1
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,6 @@
33

44

55
import numpy as np
6-
import six
76
from numpy.testing import assert_array_equal
87

98
from caffe2.python import core, workspace

caffe2/python/operator_test/utility_ops_test.py

+1-2
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,6 @@
1111
import hypothesis.strategies as st
1212
import numpy as np
1313
import random
14-
import six
1514

1615

1716
class TestUtilityOps(serial.SerializedTestCase):
@@ -474,7 +473,7 @@ def test_range(self, gc, dc):
474473
names[len(inputs) - 1],
475474
["Y"]
476475
)
477-
with six.assertRaisesRegex(self, RuntimeError, 'Step size cannot be 0'):
476+
with self.assertRaisesRegex(RuntimeError, 'Step size cannot be 0'):
478477
self.assertReferenceChecks(
479478
device_option=gc,
480479
op=op,

caffe2/python/parallel_workers.py

+1-2
Original file line numberDiff line numberDiff line change
@@ -38,7 +38,6 @@
3838
import atexit
3939
import time
4040
import collections
41-
import six
4241
import traceback
4342

4443
from abc import ABCMeta, abstractmethod
@@ -110,7 +109,7 @@ def put_metric(self, key, value, count=True):
110109

111110

112111
class State():
113-
six.add_metaclass(ABCMeta)
112+
__metaclass__ = ABCMeta
114113

115114
@abstractmethod
116115
def start(self):

caffe2/python/python_op_test.py

+2-3
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,6 @@
88
from hypothesis import given, settings
99
import hypothesis.strategies as st
1010
import numpy as np
11-
import six
1211

1312

1413
class CustomError(Exception):
@@ -55,12 +54,12 @@ def f(inputs, _):
5554

5655
def test_exception(self):
5756
op = CreatePythonOperator(MainOpFunctionThatThrowsCustomError, [], [])
58-
with six.assertRaisesRegex(self, CustomError, "This is an intentional exception."):
57+
with self.assertRaisesRegex(CustomError, "This is an intentional exception."):
5958
workspace.RunOperatorOnce(op)
6059

6160
def test_exception_builder(self):
6261
op = CreatePythonOperator(MainOpFunctionThatThrowsCustomErrorInBuilder, [], [])
63-
with six.assertRaisesRegex(self, CustomError, "This is an intentional exception in builder."):
62+
with self.assertRaisesRegex(CustomError, "This is an intentional exception in builder."):
6463
workspace.RunOperatorOnce(op)
6564

6665
@given(x=hu.tensor())

caffe2/python/rnn_cell.py

+1-2
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,6 @@
1111
import logging
1212
import numpy as np
1313
import random
14-
import six
1514
from future.utils import viewkeys
1615

1716
from caffe2.proto import caffe2_pb2
@@ -32,7 +31,7 @@
3231
def _RectifyName(blob_reference_or_name):
3332
if blob_reference_or_name is None:
3433
return None
35-
if isinstance(blob_reference_or_name, six.string_types):
34+
if isinstance(blob_reference_or_name, str):
3635
return core.ScopedBlobReference(blob_reference_or_name)
3736
if not isinstance(blob_reference_or_name, core.BlobReference):
3837
raise Exception("Unknown blob reference type")

0 commit comments

Comments
 (0)