Skip to content

Commit a960395

Browse files
authored
Merge pull request #289 from MeggyCal/master
clear some Python 2 remnants (including six)
2 parents 2b74b09 + 0c6fa36 commit a960395

File tree

10 files changed

+55
-80
lines changed

10 files changed

+55
-80
lines changed

python_jsonschema_objects/__init__.py

Lines changed: 5 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,6 @@
1414
import referencing.jsonschema
1515
import referencing.retrieval
1616
import referencing._core
17-
import six
1817
from referencing import Registry, Resource
1918

2019
import python_jsonschema_objects.classbuilder as classbuilder
@@ -43,7 +42,7 @@ def __init__(
4342
resolver: Optional[referencing.typing.Retrieve] = None,
4443
specification_uri: Optional[str] = None,
4544
):
46-
if isinstance(schema_uri, six.string_types):
45+
if isinstance(schema_uri, str):
4746
uri = os.path.normpath(schema_uri)
4847
self.basedir = os.path.dirname(uri)
4948
with codecs.open(uri, "r", "utf-8") as fin:
@@ -220,7 +219,7 @@ def build_classes(
220219
"""
221220
kw = {"strict": strict, "any_of": any_of}
222221
builder = classbuilder.ClassBuilder(self.resolver)
223-
for nm, defn in six.iteritems(self.schema.get("definitions", {})):
222+
for nm, defn in self.schema.get("definitions", {}).items():
224223
resolved = self.resolver.lookup("#/definitions/" + nm)
225224
uri = python_jsonschema_objects.util.resolve_ref_uri(
226225
self.resolver._base_uri, "#/definitions/" + nm
@@ -229,19 +228,19 @@ def build_classes(
229228

230229
if standardize_names:
231230
name_transform = lambda t: inflection.camelize(
232-
inflection.parameterize(six.text_type(t), "_")
231+
inflection.parameterize(str(t), "_")
233232
)
234233
else:
235234
name_transform = lambda t: t
236235

237236
nm = self.schema["title"] if "title" in self.schema else self.schema["$id"]
238-
nm = inflection.parameterize(six.text_type(nm), "_")
237+
nm = inflection.parameterize(str(nm), "_")
239238

240239
builder.construct(nm, self.schema, **kw)
241240
self._resolved = builder.resolved
242241

243242
classes = {}
244-
for uri, klass in six.iteritems(builder.resolved):
243+
for uri, klass in builder.resolved.items():
245244
title = getattr(klass, "__title__", None)
246245
if title is not None:
247246
classes[name_transform(title)] = klass

python_jsonschema_objects/classbuilder.py

Lines changed: 30 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,6 @@
66

77
import jsonschema.exceptions
88
import referencing._core
9-
import six
109

1110
from python_jsonschema_objects import (
1211
pattern_properties,
@@ -81,26 +80,26 @@ def __eq__(self, other):
8180
return self.as_dict() == other.as_dict()
8281

8382
def __str__(self):
84-
inverter = dict((v, k) for k, v in six.iteritems(self.__prop_names__))
83+
inverter = dict((v, k) for k, v in self.__prop_names__.items())
8584
props = sorted(
8685
[
8786
"%s" % (inverter.get(k, k),)
8887
for k, v in itertools.chain(
89-
six.iteritems(self._properties),
90-
six.iteritems(self._extended_properties),
88+
self._properties.items(),
89+
self._extended_properties.items(),
9190
)
9291
]
9392
)
9493
return "<%s attributes: %s>" % (self.__class__.__name__, ", ".join(props))
9594

9695
def __repr__(self):
97-
inverter = dict((v, k) for k, v in six.iteritems(self.__prop_names__))
96+
inverter = dict((v, k) for k, v in self.__prop_names__.items())
9897
props = sorted(
9998
[
10099
"%s=%s" % (inverter.get(k, k), repr(v))
101100
for k, v in itertools.chain(
102-
six.iteritems(self._properties),
103-
six.iteritems(self._extended_properties),
101+
self._properties.items(),
102+
self._extended_properties.items(),
104103
)
105104
]
106105
)
@@ -177,7 +176,7 @@ def __init__(self, **props):
177176
self._properties = dict(
178177
zip(
179178
self.__prop_names__.values(),
180-
[None for x in six.moves.xrange(len(self.__prop_names__))],
179+
[None for x in range(len(self.__prop_names__))],
181180
)
182181
)
183182

@@ -216,16 +215,13 @@ def __init__(self, **props):
216215
except validators.ValidationError as e:
217216
import sys
218217

219-
raise six.reraise(
220-
type(e),
221-
type(e)(
222-
str(e)
223-
+ " \nwhile setting '{0}' in {1}".format(
224-
prop, self.__class__.__name__
225-
)
226-
),
227-
sys.exc_info()[2],
218+
e = type(e)(
219+
str(e)
220+
+ " \nwhile setting '{0}' in {1}".format(
221+
prop, self.__class__.__name__
222+
)
228223
)
224+
raise e.with_traceback(sys.exc_info()[2])
229225

230226
if getattr(self, "__strict__", None):
231227
self.validate()
@@ -258,7 +254,7 @@ def __iter__(self):
258254
import itertools
259255

260256
return itertools.chain(
261-
six.iterkeys(self._extended_properties), six.iterkeys(self._properties)
257+
self._extended_properties.keys(), self._properties.keys()
262258
)
263259

264260
def __len__(self):
@@ -330,7 +326,7 @@ def validate(self):
330326
)
331327
)
332328

333-
for prop, val in six.iteritems(self._properties):
329+
for prop, val in self._properties.items():
334330
if val is None:
335331
continue
336332
if isinstance(val, ProtocolBase):
@@ -593,7 +589,7 @@ def _construct(self, uri, clsdata, parent=(ProtocolBase,), **kw):
593589
elif isinstance(clsdata.get("type"), list):
594590
types = []
595591
for i, item_detail in enumerate(clsdata["type"]):
596-
subdata = {k: v for k, v in six.iteritems(clsdata) if k != "type"}
592+
subdata = {k: v for k, v in clsdata.items() if k != "type"}
597593
subdata["type"] = item_detail
598594
types.append(self._build_literal(uri + "_%s" % i, subdata))
599595

@@ -642,13 +638,15 @@ def _build_literal(self, nm, clsdata):
642638
# This weird value on the next line is a sentinel value, because we can't use the standard `get(
643639
# "key", None) is not None` motif because sometimes the value is None. If someone has an actual
644640
# value like this (which I generated by having my cat walk on my keyboard), they're out of luck.
645-
"__default__": clsdata["default"]
646-
if clsdata.get(
647-
"default",
648-
"asldkfn24olkjalskdfn e;laishd;1loj;flkansd;iow;naosdinfe;lkamjsdfj",
649-
)
650-
is not "asldkfn24olkjalskdfn e;laishd;1loj;flkansd;iow;naosdinfe;lkamjsdfj"
651-
else clsdata.get("const"),
641+
"__default__": (
642+
clsdata["default"]
643+
if clsdata.get(
644+
"default",
645+
"asldkfn24olkjalskdfn e;laishd;1loj;flkansd;iow;naosdinfe;lkamjsdfj",
646+
)
647+
is not "asldkfn24olkjalskdfn e;laishd;1loj;flkansd;iow;naosdinfe;lkamjsdfj"
648+
else clsdata.get("const")
649+
),
652650
}
653651
},
654652
)
@@ -824,9 +822,11 @@ def _build_object(self, nm, clsdata, parents, **kw):
824822

825823
def construct_objects(self, oneOfList, uri):
826824
return [
827-
self.construct(uri + "_%s" % i, item_detail)
828-
if "$ref" not in item_detail
829-
else self.resolve_type(item_detail["$ref"], uri + "_%s" % i)
825+
(
826+
self.construct(uri + "_%s" % i, item_detail)
827+
if "$ref" not in item_detail
828+
else self.resolve_type(item_detail["$ref"], uri + "_%s" % i)
829+
)
830830
for i, item_detail in enumerate(oneOfList)
831831
]
832832

python_jsonschema_objects/descriptors.py

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -60,7 +60,7 @@ def __set__(self, obj, val):
6060
elif util.safe_issubclass(typ, ProtocolBase):
6161
# Force conversion- thus the val rather than validator assignment.
6262
try:
63-
val = typ(**util.coerce_for_expansion(val))
63+
val = typ(**val)
6464
val.validate()
6565
except Exception as e:
6666
errors.append("Failed to coerce to '{0}': {1}".format(typ, e))
@@ -82,7 +82,6 @@ def __set__(self, obj, val):
8282
try:
8383
# Handle keyword expansion according to expected types. Using
8484
# keywords like oneOf, value can be an object, array or literal.
85-
val = util.coerce_for_expansion(val)
8685
if isinstance(val, dict):
8786
val = typ(**val)
8887
else:
@@ -120,12 +119,11 @@ def __set__(self, obj, val):
120119

121120
elif util.safe_issubclass(info["type"], ProtocolBase):
122121
if not isinstance(val, info["type"]):
123-
val = info["type"](**util.coerce_for_expansion(val))
122+
val = info["type"](**val)
124123

125124
val.validate()
126125

127126
elif isinstance(info["type"], TypeProxy):
128-
val = util.coerce_for_expansion(val)
129127
if isinstance(val, dict):
130128
val = info["type"](**val)
131129
else:

python_jsonschema_objects/literals.py

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,6 @@
11
import functools
22
import operator
33

4-
import six
54

65
from python_jsonschema_objects import util, validators
76

@@ -74,7 +73,7 @@ def __repr__(self):
7473
return "<Literal<%s> %s>" % (self._value.__class__.__name__, str(self._value))
7574

7675
def __str__(self):
77-
if isinstance(self._value, six.string_types):
76+
if isinstance(self._value, str):
7877
return self._value
7978
return str(self._value)
8079

@@ -84,7 +83,7 @@ def validate(self):
8483
# TODO: this duplicates logic in validators.ArrayValidator.check_items;
8584
# unify it.
8685
for param, paramval in sorted(
87-
six.iteritems(info), key=lambda x: x[0].lower() != "type"
86+
info.items(), key=lambda x: x[0].lower() != "type"
8887
):
8988
validator = validators.registry(param)
9089
if validator is not None:

python_jsonschema_objects/pattern_properties.py

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,6 @@
22
import logging
33
import re
44

5-
import six
65

76
from python_jsonschema_objects import util, validators, wrapper_types
87
from python_jsonschema_objects.literals import MakeLiteral
@@ -39,7 +38,7 @@ def __init__(self, name, schemadef, builder):
3938

4039
self._additional_type = typ
4140

42-
for pattern, typedef in six.iteritems(schemadef.get("patternProperties", {})):
41+
for pattern, typedef in schemadef.get("patternProperties", {}).items():
4342
if "$ref" in typedef:
4443
typ = builder.resolve_type(typedef["$ref"], name)
4544
else:
@@ -61,13 +60,12 @@ def _make_type(self, typ, val):
6160
return typ(val)
6261

6362
if util.safe_issubclass(typ, cb.ProtocolBase):
64-
return typ(**util.coerce_for_expansion(val))
63+
return typ(**val)
6564

6665
if util.safe_issubclass(typ, wrapper_types.ArrayWrapper):
6766
return typ(val)
6867

6968
if isinstance(typ, cb.TypeProxy):
70-
val = util.coerce_for_expansion(val)
7169
if isinstance(val, dict):
7270
val = typ(**val)
7371
else:

python_jsonschema_objects/util.py

Lines changed: 2 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -6,8 +6,6 @@
66
import json
77
from collections.abc import Mapping, Sequence
88

9-
import six
10-
119

1210
class lazy_format(object):
1311
__slots__ = ("fmt", "args", "kwargs")
@@ -36,18 +34,6 @@ def safe_issubclass(x, y):
3634
return False
3735

3836

39-
def coerce_for_expansion(mapping):
40-
"""Given a value, make sure it is usable for f(**val) expansion.
41-
42-
In py2.7, the value must be a dictionary- thus a as_dict() method
43-
will be invoked if available. In py3k, the raw mapping is returned
44-
unmodified.
45-
"""
46-
if six.PY2 and hasattr(mapping, "as_dict"):
47-
return mapping.as_dict()
48-
return mapping
49-
50-
5137
class ProtocolJSONEncoder(json.JSONEncoder):
5238
def default(self, obj):
5339
from python_jsonschema_objects import classbuilder, wrapper_types
@@ -69,13 +55,13 @@ def propmerge(into, data_from):
6955
"""Merge JSON schema requirements into a dictionary"""
7056
newprops = copy.deepcopy(into)
7157

72-
for prop, propval in six.iteritems(data_from):
58+
for prop, propval in data_from.items():
7359
if prop not in newprops:
7460
newprops[prop] = propval
7561
continue
7662

7763
new_sp = newprops[prop]
78-
for subprop, spval in six.iteritems(propval):
64+
for subprop, spval in propval.items():
7965
if subprop not in new_sp:
8066
new_sp[subprop] = spval
8167

python_jsonschema_objects/validators.py

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,17 +1,17 @@
11
import decimal
22
import logging
3+
import numbers
34

4-
import six
55

66
logger = logging.getLogger(__name__)
77

88
SCHEMA_TYPE_MAPPING = (
99
("array", list),
1010
("boolean", bool),
11-
("integer", six.integer_types),
12-
("number", six.integer_types + (float,)),
11+
("integer", int),
12+
("number", numbers.Real),
1313
("null", type(None)),
14-
("string", six.string_types),
14+
("string", str),
1515
("object", dict),
1616
)
1717
"""Sequence of schema type mappings to be checked in precedence order."""
@@ -140,7 +140,7 @@ def check_integer_type(param, value, _):
140140

141141
@type_registry.register(name="number")
142142
def check_number_type(param, value, _):
143-
if not isinstance(value, six.integer_types + (float,)) or isinstance(value, bool):
143+
if not isinstance(value, numbers.Real):
144144
raise ValidationError("{0} is neither an integer nor a float".format(value))
145145

146146

@@ -152,7 +152,7 @@ def check_null_type(param, value, _):
152152

153153
@type_registry.register(name="string")
154154
def check_string_type(param, value, _):
155-
if not isinstance(value, six.string_types):
155+
if not isinstance(value, str):
156156
raise ValidationError("{0} is not a string".format(value))
157157

158158

0 commit comments

Comments
 (0)