Skip to content

Commit

Permalink
normalize strings
Browse files Browse the repository at this point in the history
  • Loading branch information
antoni-szych-rtbhouse committed Dec 15, 2023
1 parent 10e984c commit 503f7da
Show file tree
Hide file tree
Showing 10 changed files with 394 additions and 395 deletions.
1 change: 0 additions & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
[tool.black]
target-version = ["py38", "py39", "py310", "py311", "py312"]
skip-string-normalization = true

[tool.isort]
skip_gitignore = true
Expand Down
48 changes: 24 additions & 24 deletions setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,41 +3,41 @@

from setuptools import setup

sys.path.insert(0, '.')
version = __import__('voluptuous').__version__
sys.path.insert(0, ".")
version = __import__("voluptuous").__version__


with io.open('README.md', encoding='utf-8') as f:
with io.open("README.md", encoding="utf-8") as f:
long_description = f.read()


setup(
name='voluptuous',
url='https://github.com/alecthomas/voluptuous',
download_url='https://pypi.python.org/pypi/voluptuous',
name="voluptuous",
url="https://github.com/alecthomas/voluptuous",
download_url="https://pypi.python.org/pypi/voluptuous",
version=version,
description='Python data validation library',
description="Python data validation library",
long_description=long_description,
long_description_content_type='text/markdown',
license='BSD-3-Clause',
platforms=['any'],
packages=['voluptuous'],
long_description_content_type="text/markdown",
license="BSD-3-Clause",
platforms=["any"],
packages=["voluptuous"],
package_data={
'voluptuous': ['py.typed'],
"voluptuous": ["py.typed"],
},
author='Alec Thomas',
author_email='[email protected]',
author="Alec Thomas",
author_email="[email protected]",
python_requires=">=3.8",
classifiers=[
'Development Status :: 5 - Production/Stable',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.8',
'Programming Language :: Python :: 3.9',
'Programming Language :: Python :: 3.10',
'Programming Language :: Python :: 3.11',
'Programming Language :: Python :: 3.12',
"Development Status :: 5 - Production/Stable",
"Intended Audience :: Developers",
"License :: OSI Approved :: BSD License",
"Operating System :: OS Independent",
"Programming Language :: Python :: 3",
"Programming Language :: Python :: 3.8",
"Programming Language :: Python :: 3.9",
"Programming Language :: Python :: 3.10",
"Programming Language :: Python :: 3.11",
"Programming Language :: Python :: 3.12",
],
)
4 changes: 2 additions & 2 deletions voluptuous/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,5 +8,5 @@

# fmt: on

__version__ = '0.14.1'
__author__ = 'alecthomas'
__version__ = "0.14.1"
__author__ = "alecthomas"
6 changes: 3 additions & 3 deletions voluptuous/error.py
Original file line number Diff line number Diff line change
Expand Up @@ -47,10 +47,10 @@ def error_message(self) -> str:
return self._error_message

def __str__(self) -> str:
path = ' @ data[%s]' % ']['.join(map(repr, self.path)) if self.path else ''
path = " @ data[%s]" % "][".join(map(repr, self.path)) if self.path else ""
output = Exception.__str__(self)
if self.error_type:
output += ' for ' + self.error_type
output += " for " + self.error_type
return output + path

def prepend(self, path: typing.List[typing.Hashable]) -> None:
Expand All @@ -62,7 +62,7 @@ def __init__(self, errors: typing.Optional[typing.List[Invalid]] = None) -> None
self.errors = errors[:] if errors else []

def __repr__(self) -> str:
return 'MultipleInvalid(%r)' % self.errors
return "MultipleInvalid(%r)" % self.errors

@property
def msg(self) -> str:
Expand Down
6 changes: 3 additions & 3 deletions voluptuous/humanize.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ def humanize_error(
and MultipleInvalid.__str__ only provides the first error.
"""
if isinstance(validation_error, MultipleInvalid):
return '\n'.join(
return "\n".join(
sorted(
humanize_error(data, sub_error, max_sub_error_length)
for sub_error in validation_error.errors
Expand All @@ -43,9 +43,9 @@ def humanize_error(
offending_item_summary = repr(_nested_getitem(data, validation_error.path))
if len(offending_item_summary) > max_sub_error_length:
offending_item_summary = (
offending_item_summary[: max_sub_error_length - 3] + '...'
offending_item_summary[: max_sub_error_length - 3] + "..."
)
return '%s. Got %s' % (validation_error, offending_item_summary)
return "%s. Got %s" % (validation_error, offending_item_summary)


def validate_with_humanized_errors(
Expand Down
68 changes: 34 additions & 34 deletions voluptuous/schema_builder.py
Original file line number Diff line number Diff line change
Expand Up @@ -99,15 +99,15 @@


def _isnamedtuple(obj):
return isinstance(obj, tuple) and hasattr(obj, '_fields')
return isinstance(obj, tuple) and hasattr(obj, "_fields")


class Undefined(object):
def __nonzero__(self):
return False

def __repr__(self):
return '...'
return "..."


UNDEFINED = Undefined()
Expand All @@ -134,9 +134,9 @@ def raises(
yield
except exc as e:
if msg is not None:
assert str(e) == msg, '%r != %r' % (str(e), msg)
assert str(e) == msg, "%r != %r" % (str(e), msg)
if regex is not None:
assert re.search(regex, str(e)), '%r does not match %r' % (str(e), regex)
assert re.search(regex, str(e)), "%r does not match %r" % (str(e), regex)
else:
raise AssertionError(f"Did not raise exception {exc.__name__}")

Expand Down Expand Up @@ -186,9 +186,9 @@ class Schema(object):
"""

_extra_to_name = {
REMOVE_EXTRA: 'REMOVE_EXTRA',
ALLOW_EXTRA: 'ALLOW_EXTRA',
PREVENT_EXTRA: 'PREVENT_EXTRA',
REMOVE_EXTRA: "REMOVE_EXTRA",
ALLOW_EXTRA: "ALLOW_EXTRA",
PREVENT_EXTRA: "PREVENT_EXTRA",
}

def __init__(
Expand Down Expand Up @@ -270,7 +270,7 @@ def __str__(self):
def __repr__(self):
return "<Schema(%s, extra=%s, required=%s) object at 0x%x>" % (
self.schema,
self._extra_to_name.get(self.extra, '??'),
self._extra_to_name.get(self.extra, "??"),
self.required,
id(self),
)
Expand Down Expand Up @@ -307,11 +307,11 @@ def _compile(self, schema):
type_ = schema
if type_ in (*primitive_types, object, type(None)) or callable(schema):
return _compile_scalar(schema)
raise er.SchemaError('unsupported schema data type %r' % type(schema).__name__)
raise er.SchemaError("unsupported schema data type %r" % type(schema).__name__)

def _compile_mapping(self, schema, invalid_msg=None):
"""Create validator for given mapping."""
invalid_msg = invalid_msg or 'mapping value'
invalid_msg = invalid_msg or "mapping value"

# Keys that may be required
all_required_keys = set(
Expand Down Expand Up @@ -443,15 +443,15 @@ def validate_mapping(path, iterable, out):
elif self.extra == ALLOW_EXTRA:
out[key] = value
elif self.extra != REMOVE_EXTRA:
errors.append(er.Invalid('extra keys not allowed', key_path))
errors.append(er.Invalid("extra keys not allowed", key_path))
# else REMOVE_EXTRA: ignore the key so it's removed from output

# for any required keys left that weren't found and don't have defaults:
for key in required_keys:
msg = (
key.msg
if hasattr(key, 'msg') and key.msg
else 'required key not provided'
if hasattr(key, "msg") and key.msg
else "required key not provided"
)
errors.append(er.RequiredFieldInvalid(msg, path + [key]))
if errors:
Expand Down Expand Up @@ -479,11 +479,11 @@ def _compile_object(self, schema):
... validate(Structure(one='three'))
"""
base_validate = self._compile_mapping(schema, invalid_msg='object value')
base_validate = self._compile_mapping(schema, invalid_msg="object value")

def validate_object(path, data):
if schema.cls is not UNDEFINED and not isinstance(data, schema.cls):
raise er.ObjectInvalid('expected a {0!r}'.format(schema.cls), path)
raise er.ObjectInvalid("expected a {0!r}".format(schema.cls), path)
iterable = _iterate_object(data)
iterable = filter(lambda item: item[1] is not None, iterable)
out = base_validate(path, iterable, {})
Expand Down Expand Up @@ -567,7 +567,7 @@ def _compile_dict(self, schema):
"expected str for dictionary value @ data['adict']['strfield']"]
"""
base_validate = self._compile_mapping(schema, invalid_msg='dictionary value')
base_validate = self._compile_mapping(schema, invalid_msg="dictionary value")

groups_of_exclusion = {}
groups_of_inclusion = {}
Expand All @@ -581,7 +581,7 @@ def _compile_dict(self, schema):

def validate_dict(path, data):
if not isinstance(data, dict):
raise er.DictInvalid('expected a dictionary', path)
raise er.DictInvalid("expected a dictionary", path)

errors = []
for label, group in groups_of_exclusion.items():
Expand All @@ -591,7 +591,7 @@ def validate_dict(path, data):
if exists:
msg = (
exclusive.msg
if hasattr(exclusive, 'msg') and exclusive.msg
if hasattr(exclusive, "msg") and exclusive.msg
else "two or more values in the same group of exclusion '%s'"
% label
)
Expand All @@ -611,7 +611,7 @@ def validate_dict(path, data):
% label
)
for g in group:
if hasattr(g, 'msg') and g.msg:
if hasattr(g, "msg") and g.msg:
msg = g.msg
break
next_path = path + [VirtualPathComponent(label)]
Expand Down Expand Up @@ -644,13 +644,13 @@ def _compile_sequence(self, schema, seq_type):

def validate_sequence(path, data):
if not isinstance(data, seq_type):
raise er.SequenceTypeInvalid('expected a %s' % seq_type_name, path)
raise er.SequenceTypeInvalid("expected a %s" % seq_type_name, path)

# Empty seq schema, reject any data.
if not schema:
if data:
raise er.MultipleInvalid(
[er.ValueInvalid('not a valid value', path if path else data)]
[er.ValueInvalid("not a valid value", path if path else data)]
)
return data

Expand Down Expand Up @@ -731,7 +731,7 @@ def _compile_set(self, schema):

def validate_set(path, data):
if not isinstance(data, type_):
raise er.Invalid('expected a %s' % type_name, path)
raise er.Invalid("expected a %s" % type_name, path)

_compiled = [self._compile(s) for s in schema]
errors = []
Expand All @@ -743,7 +743,7 @@ def validate_set(path, data):
except er.Invalid:
pass
else:
invalid = er.Invalid('invalid value in %s' % type_name, path)
invalid = er.Invalid("invalid value in %s" % type_name, path)
errors.append(invalid)

if errors:
Expand Down Expand Up @@ -774,7 +774,7 @@ def extend(

assert isinstance(self.schema, dict) and isinstance(
schema, dict
), 'Both schemas must be dictionary-based'
), "Both schemas must be dictionary-based"

result = self.schema.copy()

Expand Down Expand Up @@ -843,7 +843,7 @@ def validate_instance(path, data):
if isinstance(data, schema):
return data
else:
msg = 'expected %s' % schema.__name__
msg = "expected %s" % schema.__name__
raise er.TypeInvalid(msg, path)

return validate_instance
Expand All @@ -854,7 +854,7 @@ def validate_callable(path, data):
try:
return schema(data)
except ValueError:
raise er.ValueInvalid('not a valid value', path)
raise er.ValueInvalid("not a valid value", path)
except er.Invalid as e:
e.prepend(path)
raise
Expand All @@ -863,14 +863,14 @@ def validate_callable(path, data):

def validate_value(path, data):
if data != schema:
raise er.ScalarInvalid('not a valid value', path)
raise er.ScalarInvalid("not a valid value", path)
return data

return validate_value


def _compile_itemsort():
'''return sort function of mappings'''
"""return sort function of mappings"""

def is_extra(key_):
return key_ is Extra
Expand Down Expand Up @@ -932,7 +932,7 @@ def _iterate_object(obj):
d = vars(obj)
except TypeError:
# maybe we have named tuple here?
if hasattr(obj, '_asdict'):
if hasattr(obj, "_asdict"):
d = obj._asdict()
for item in d.items():
yield item
Expand All @@ -942,7 +942,7 @@ def _iterate_object(obj):
pass
else:
for key in slots:
if key != '__dict__':
if key != "__dict__":
yield (key, getattr(obj, key))


Expand Down Expand Up @@ -1000,7 +1000,7 @@ def __call__(self, v):
raise (self.cls or er.Invalid)(self.msg)

def __repr__(self):
return 'Msg(%s, %s, cls=%s)' % (self._schema, self.msg, self.cls)
return "Msg(%s, %s, cls=%s)" % (self._schema, self.msg, self.cls)


class Object(dict):
Expand All @@ -1013,7 +1013,7 @@ def __init__(self, schema: typing.Any, cls: object = UNDEFINED) -> None:

class VirtualPathComponent(str):
def __str__(self):
return '<' + self + '>'
return "<" + self + ">"

def __repr__(self):
return self.__str__()
Expand Down Expand Up @@ -1296,7 +1296,7 @@ def wrapper(*args, **kwargs):
return f(*args, **kwargs)
except ValueError:
raise (clsoverride or cls or er.ValueInvalid)(
msg or default or 'invalid value'
msg or default or "invalid value"
)

return wrapper
Expand Down Expand Up @@ -1347,7 +1347,7 @@ def validate(*a, **kw) -> typing.Callable:
... return arg1 * 2
"""
RETURNS_KEY = '__return__'
RETURNS_KEY = "__return__"

def validate_schema_decorator(func):
returns_defined = False
Expand Down
2 changes: 1 addition & 1 deletion voluptuous/tests/__init__.py
Original file line number Diff line number Diff line change
@@ -1 +1 @@
__author__ = 'tusharmakkar08'
__author__ = "tusharmakkar08"
Loading

0 comments on commit 503f7da

Please sign in to comment.