Skip to content

Commit

Permalink
Merge pull request #289 from MeggyCal/master
Browse files Browse the repository at this point in the history
clear some Python 2 remnants (including six)
  • Loading branch information
cwacek authored Jun 23, 2024
2 parents 2b74b09 + 0c6fa36 commit a960395
Show file tree
Hide file tree
Showing 10 changed files with 55 additions and 80 deletions.
11 changes: 5 additions & 6 deletions python_jsonschema_objects/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,6 @@
import referencing.jsonschema
import referencing.retrieval
import referencing._core
import six
from referencing import Registry, Resource

import python_jsonschema_objects.classbuilder as classbuilder
Expand Down Expand Up @@ -43,7 +42,7 @@ def __init__(
resolver: Optional[referencing.typing.Retrieve] = None,
specification_uri: Optional[str] = None,
):
if isinstance(schema_uri, six.string_types):
if isinstance(schema_uri, str):
uri = os.path.normpath(schema_uri)
self.basedir = os.path.dirname(uri)
with codecs.open(uri, "r", "utf-8") as fin:
Expand Down Expand Up @@ -220,7 +219,7 @@ def build_classes(
"""
kw = {"strict": strict, "any_of": any_of}
builder = classbuilder.ClassBuilder(self.resolver)
for nm, defn in six.iteritems(self.schema.get("definitions", {})):
for nm, defn in self.schema.get("definitions", {}).items():
resolved = self.resolver.lookup("#/definitions/" + nm)
uri = python_jsonschema_objects.util.resolve_ref_uri(
self.resolver._base_uri, "#/definitions/" + nm
Expand All @@ -229,19 +228,19 @@ def build_classes(

if standardize_names:
name_transform = lambda t: inflection.camelize(
inflection.parameterize(six.text_type(t), "_")
inflection.parameterize(str(t), "_")
)
else:
name_transform = lambda t: t

nm = self.schema["title"] if "title" in self.schema else self.schema["$id"]
nm = inflection.parameterize(six.text_type(nm), "_")
nm = inflection.parameterize(str(nm), "_")

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

classes = {}
for uri, klass in six.iteritems(builder.resolved):
for uri, klass in builder.resolved.items():
title = getattr(klass, "__title__", None)
if title is not None:
classes[name_transform(title)] = klass
Expand Down
60 changes: 30 additions & 30 deletions python_jsonschema_objects/classbuilder.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@

import jsonschema.exceptions
import referencing._core
import six

from python_jsonschema_objects import (
pattern_properties,
Expand Down Expand Up @@ -81,26 +80,26 @@ def __eq__(self, other):
return self.as_dict() == other.as_dict()

def __str__(self):
inverter = dict((v, k) for k, v in six.iteritems(self.__prop_names__))
inverter = dict((v, k) for k, v in self.__prop_names__.items())
props = sorted(
[
"%s" % (inverter.get(k, k),)
for k, v in itertools.chain(
six.iteritems(self._properties),
six.iteritems(self._extended_properties),
self._properties.items(),
self._extended_properties.items(),
)
]
)
return "<%s attributes: %s>" % (self.__class__.__name__, ", ".join(props))

def __repr__(self):
inverter = dict((v, k) for k, v in six.iteritems(self.__prop_names__))
inverter = dict((v, k) for k, v in self.__prop_names__.items())
props = sorted(
[
"%s=%s" % (inverter.get(k, k), repr(v))
for k, v in itertools.chain(
six.iteritems(self._properties),
six.iteritems(self._extended_properties),
self._properties.items(),
self._extended_properties.items(),
)
]
)
Expand Down Expand Up @@ -177,7 +176,7 @@ def __init__(self, **props):
self._properties = dict(
zip(
self.__prop_names__.values(),
[None for x in six.moves.xrange(len(self.__prop_names__))],
[None for x in range(len(self.__prop_names__))],
)
)

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

raise six.reraise(
type(e),
type(e)(
str(e)
+ " \nwhile setting '{0}' in {1}".format(
prop, self.__class__.__name__
)
),
sys.exc_info()[2],
e = type(e)(
str(e)
+ " \nwhile setting '{0}' in {1}".format(
prop, self.__class__.__name__
)
)
raise e.with_traceback(sys.exc_info()[2])

if getattr(self, "__strict__", None):
self.validate()
Expand Down Expand Up @@ -258,7 +254,7 @@ def __iter__(self):
import itertools

return itertools.chain(
six.iterkeys(self._extended_properties), six.iterkeys(self._properties)
self._extended_properties.keys(), self._properties.keys()
)

def __len__(self):
Expand Down Expand Up @@ -330,7 +326,7 @@ def validate(self):
)
)

for prop, val in six.iteritems(self._properties):
for prop, val in self._properties.items():
if val is None:
continue
if isinstance(val, ProtocolBase):
Expand Down Expand Up @@ -593,7 +589,7 @@ def _construct(self, uri, clsdata, parent=(ProtocolBase,), **kw):
elif isinstance(clsdata.get("type"), list):
types = []
for i, item_detail in enumerate(clsdata["type"]):
subdata = {k: v for k, v in six.iteritems(clsdata) if k != "type"}
subdata = {k: v for k, v in clsdata.items() if k != "type"}
subdata["type"] = item_detail
types.append(self._build_literal(uri + "_%s" % i, subdata))

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

def construct_objects(self, oneOfList, uri):
return [
self.construct(uri + "_%s" % i, item_detail)
if "$ref" not in item_detail
else self.resolve_type(item_detail["$ref"], uri + "_%s" % i)
(
self.construct(uri + "_%s" % i, item_detail)
if "$ref" not in item_detail
else self.resolve_type(item_detail["$ref"], uri + "_%s" % i)
)
for i, item_detail in enumerate(oneOfList)
]

Expand Down
6 changes: 2 additions & 4 deletions python_jsonschema_objects/descriptors.py
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,7 @@ def __set__(self, obj, val):
elif util.safe_issubclass(typ, ProtocolBase):
# Force conversion- thus the val rather than validator assignment.
try:
val = typ(**util.coerce_for_expansion(val))
val = typ(**val)
val.validate()
except Exception as e:
errors.append("Failed to coerce to '{0}': {1}".format(typ, e))
Expand All @@ -82,7 +82,6 @@ def __set__(self, obj, val):
try:
# Handle keyword expansion according to expected types. Using
# keywords like oneOf, value can be an object, array or literal.
val = util.coerce_for_expansion(val)
if isinstance(val, dict):
val = typ(**val)
else:
Expand Down Expand Up @@ -120,12 +119,11 @@ def __set__(self, obj, val):

elif util.safe_issubclass(info["type"], ProtocolBase):
if not isinstance(val, info["type"]):
val = info["type"](**util.coerce_for_expansion(val))
val = info["type"](**val)

val.validate()

elif isinstance(info["type"], TypeProxy):
val = util.coerce_for_expansion(val)
if isinstance(val, dict):
val = info["type"](**val)
else:
Expand Down
5 changes: 2 additions & 3 deletions python_jsonschema_objects/literals.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
import functools
import operator

import six

from python_jsonschema_objects import util, validators

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

def __str__(self):
if isinstance(self._value, six.string_types):
if isinstance(self._value, str):
return self._value
return str(self._value)

Expand All @@ -84,7 +83,7 @@ def validate(self):
# TODO: this duplicates logic in validators.ArrayValidator.check_items;
# unify it.
for param, paramval in sorted(
six.iteritems(info), key=lambda x: x[0].lower() != "type"
info.items(), key=lambda x: x[0].lower() != "type"
):
validator = validators.registry(param)
if validator is not None:
Expand Down
6 changes: 2 additions & 4 deletions python_jsonschema_objects/pattern_properties.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@
import logging
import re

import six

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

self._additional_type = typ

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

if util.safe_issubclass(typ, cb.ProtocolBase):
return typ(**util.coerce_for_expansion(val))
return typ(**val)

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

if isinstance(typ, cb.TypeProxy):
val = util.coerce_for_expansion(val)
if isinstance(val, dict):
val = typ(**val)
else:
Expand Down
18 changes: 2 additions & 16 deletions python_jsonschema_objects/util.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,6 @@
import json
from collections.abc import Mapping, Sequence

import six


class lazy_format(object):
__slots__ = ("fmt", "args", "kwargs")
Expand Down Expand Up @@ -36,18 +34,6 @@ def safe_issubclass(x, y):
return False


def coerce_for_expansion(mapping):
"""Given a value, make sure it is usable for f(**val) expansion.
In py2.7, the value must be a dictionary- thus a as_dict() method
will be invoked if available. In py3k, the raw mapping is returned
unmodified.
"""
if six.PY2 and hasattr(mapping, "as_dict"):
return mapping.as_dict()
return mapping


class ProtocolJSONEncoder(json.JSONEncoder):
def default(self, obj):
from python_jsonschema_objects import classbuilder, wrapper_types
Expand All @@ -69,13 +55,13 @@ def propmerge(into, data_from):
"""Merge JSON schema requirements into a dictionary"""
newprops = copy.deepcopy(into)

for prop, propval in six.iteritems(data_from):
for prop, propval in data_from.items():
if prop not in newprops:
newprops[prop] = propval
continue

new_sp = newprops[prop]
for subprop, spval in six.iteritems(propval):
for subprop, spval in propval.items():
if subprop not in new_sp:
new_sp[subprop] = spval

Expand Down
12 changes: 6 additions & 6 deletions python_jsonschema_objects/validators.py
Original file line number Diff line number Diff line change
@@ -1,17 +1,17 @@
import decimal
import logging
import numbers

import six

logger = logging.getLogger(__name__)

SCHEMA_TYPE_MAPPING = (
("array", list),
("boolean", bool),
("integer", six.integer_types),
("number", six.integer_types + (float,)),
("integer", int),
("number", numbers.Real),
("null", type(None)),
("string", six.string_types),
("string", str),
("object", dict),
)
"""Sequence of schema type mappings to be checked in precedence order."""
Expand Down Expand Up @@ -140,7 +140,7 @@ def check_integer_type(param, value, _):

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


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

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


Expand Down
Loading

0 comments on commit a960395

Please sign in to comment.