Skip to content

Commit 55ae80d

Browse files
committed
Clean up to make it ruff enough
1 parent 9493aa9 commit 55ae80d

35 files changed

Lines changed: 226 additions & 216 deletions

src/odin/annotated_resource/type_resolution.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -239,7 +239,7 @@ def _resolve_field_from_sub_scripted_type(origin: Type, options: Options, type_)
239239
options.field_type = ConstantField
240240
value = options.field_args["default"]
241241
if value is NotProvided:
242-
raise ResourceDefError(f"Final fields require a value")
242+
raise ResourceDefError("Final fields require a value")
243243
options.base_args["value"] = value
244244
return
245245

src/odin/codecs/json_codec.py

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -40,10 +40,13 @@ def default(self, o):
4040
if self.include_type_field:
4141
obj[meta.type_field] = meta.resource_name
4242
return obj
43+
4344
elif isinstance(o, LIST_TYPES):
4445
return list(o)
46+
4547
elif o.__class__ in JSON_TYPES:
4648
return JSON_TYPES[o.__class__](o)
49+
4750
return super().default(o)
4851

4952

@@ -88,7 +91,7 @@ def loads(s, resource=None, full_clean=True, default_to_not_supplied=False):
8891
json.loads(s), resource, full_clean, False, default_to_not_supplied
8992
)
9093
except (ValueError, TypeError) as ex:
91-
raise CodecDecodeError(str(ex))
94+
raise CodecDecodeError(str(ex)) from ex
9295

9396

9497
def dump(resource, fp, cls=OdinEncoder, **kwargs):
@@ -103,7 +106,7 @@ def dump(resource, fp, cls=OdinEncoder, **kwargs):
103106
try:
104107
json.dump(resource, fp, cls=cls, **kwargs)
105108
except ValueError as ex:
106-
raise CodecEncodeError(str(ex))
109+
raise CodecEncodeError(str(ex)) from ex
107110

108111

109112
def dumps(resource, cls=OdinEncoder, **kwargs):
@@ -118,4 +121,4 @@ def dumps(resource, cls=OdinEncoder, **kwargs):
118121
try:
119122
return json.dumps(resource, cls=cls, **kwargs)
120123
except ValueError as ex:
121-
raise CodecEncodeError(str(ex))
124+
raise CodecEncodeError(str(ex)) from ex

src/odin/codecs/msgpack_codec.py

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@
88
except ImportError:
99
raise ImportError(
1010
"odin.codecs.msgpack_codec requires the 'msgpack-python' package."
11-
) # noqa
11+
) from None # noqa
1212

1313
from odin import ResourceAdapter, bases, resources, serializers
1414
from odin.utils import getmeta
@@ -36,8 +36,10 @@ def default(self, o):
3636
obj = o.to_dict(self.include_virtual_fields)
3737
obj[meta.type_field] = meta.resource_name
3838
return obj
39+
3940
elif isinstance(o, bases.ResourceIterable):
4041
return list(o)
42+
4143
elif o.__class__ in TYPE_SERIALIZERS:
4244
return TYPE_SERIALIZERS[o.__class__](o)
4345

src/odin/codecs/toml_codec.py

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@
1010
except ImportError: # pragma: no cover
1111
raise ImportError( # pragma: no cover
1212
"odin.codecs.toml_codec requires the 'toml' package."
13-
)
13+
) from None
1414

1515

1616
TOML_TYPES = {}
@@ -39,7 +39,8 @@ def load(fp, resource=None, full_clean=True, default_to_not_supplied=False):
3939
try:
4040
data = toml.load(fp)
4141
except toml.TomlDecodeError as ex:
42-
raise CodecDecodeError(str(ex))
42+
raise CodecDecodeError(str(ex)) from ex
43+
4344
return resources.build_object_graph(
4445
data,
4546
resource,
@@ -70,7 +71,8 @@ def loads(s, resource=None, full_clean=True, default_to_not_supplied=False):
7071
try:
7172
data = toml.loads(s)
7273
except toml.TomlDecodeError as ex:
73-
raise CodecDecodeError(str(ex))
74+
raise CodecDecodeError(str(ex)) from ex
75+
7476
return resources.build_object_graph(
7577
data,
7678
resource,
@@ -105,6 +107,7 @@ def dump_value(self, v):
105107
if isinstance(v, (ResourceBase, ResourceAdapter)):
106108
resource_dict = self.resource_to_dict(v)
107109
return self.dump_inline_table(resource_dict)
110+
108111
if type(v) in TOML_TYPES:
109112
v = TOML_TYPES[type(v)](v)
110113
return super().dump_value(v)

src/odin/codecs/xml_codec.py

Lines changed: 6 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,7 @@
1919
from typing import TextIO
2020
from xml.sax import saxutils
2121

22-
from odin import Resource, fields, serializers
22+
from odin import fields, serializers
2323
from odin.fields import StringField, composite
2424
from odin.utils import attribute_field_iter_items, element_field_iter_items, getmeta
2525

@@ -48,7 +48,7 @@ def _serialize_to_string(value):
4848
def dump(
4949
fp: TextIO,
5050
resource, # type: Resource
51-
line_ending="", # type: str
51+
line_ending: str = "",
5252
):
5353
"""
5454
Dump a resource to a file like object.
@@ -60,9 +60,7 @@ def dump(
6060

6161
# Write container and any attributes
6262
attributes = "".join(
63-
" {}={}".format(
64-
f.name, saxutils.quoteattr(_serialize_to_string(v))
65-
) # Encode attributes
63+
f" {f.name}={saxutils.quoteattr(_serialize_to_string(v))}" # Encode attributes
6664
for f, v in attribute_field_iter_items(resource)
6765
)
6866
fp.write(f"<{meta.name}{attributes}>{line_ending}")
@@ -84,27 +82,16 @@ def dump(
8482
elif isinstance(field, fields.ArrayField):
8583
for v in value:
8684
fp.write(
87-
"<{}>{}</{}>{}".format(
88-
field.name, _serialize_to_string(v), field.name, line_ending
89-
)
85+
f"<{field.name}>{_serialize_to_string(v)}</{field.name}>{line_ending}"
9086
)
9187

9288
elif isinstance(field, TextField):
9389
if value is not None:
94-
fp.write(
95-
"{}{}".format(
96-
saxutils.escape(_serialize_to_string(value)), line_ending
97-
)
98-
)
90+
fp.write(f"{saxutils.escape(_serialize_to_string(value))}{line_ending}")
9991

10092
else:
10193
fp.write(
102-
"<{}>{}</{}>{}".format(
103-
field.name,
104-
saxutils.escape(_serialize_to_string(value)),
105-
field.name,
106-
line_ending,
107-
)
94+
f"<{field.name}>{saxutils.escape(_serialize_to_string(value))}</{field.name}>{line_ending}"
10895
)
10996

11097
fp.write(f"</{meta.name}>{line_ending}")

src/odin/codecs/yaml_codec.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@
1111
except ImportError:
1212
raise ImportError( # pragma: no cover
1313
"odin.codecs.yaml_codec requires the 'pyyaml' package."
14-
)
14+
) from None
1515

1616
try:
1717
from yaml import CSafeDumper as SafeDumper
@@ -96,7 +96,7 @@ def dump(resource: resources.ResourceBase, fp: TextIO, dumper=OdinDumper, **kwar
9696
try:
9797
yaml.dump(resource, fp, Dumper=dumper, **kwargs)
9898
except ValueError as ex:
99-
raise CodecEncodeError(str(ex))
99+
raise CodecEncodeError(str(ex)) from ex
100100

101101

102102
def dumps(resource: resources.ResourceBase, dumper=OdinDumper, **kwargs) -> str:

src/odin/compatibility.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@ def wrapped_init(*args, **kwargs):
2121
warnings.warn(
2222
f"{obj.__name__} is deprecated and scheduled for removal. {message}",
2323
category=category,
24+
stacklevel=2,
2425
)
2526
return old_init(*args, **kwargs)
2627

@@ -33,6 +34,7 @@ def wrapped_func(*args, **kwargs):
3334
warnings.warn(
3435
f"{obj.__name__} is deprecated and scheduled for removal. {message}",
3536
category=category,
37+
stacklevel=2,
3638
)
3739
return obj(*args, **kwargs)
3840

src/odin/contrib/arrow/__init__.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
try:
22
import arrow
33
except ImportError:
4-
raise ImportError("The arrow package is not installed.")
4+
raise ImportError("The arrow package is not installed.") from None
55

66
try:
77
from odin.codecs.json_codec import JSON_TYPES

src/odin/contrib/geo/datatypes.py

Lines changed: 5 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,10 @@
11
import math
2+
from typing import Tuple
23

34
__all__ = ("latitude", "longitude", "latlng", "point")
45

5-
from typing import Tuple
6-
76

8-
def to_dms(value, absolute=False):
9-
# type: (float, bool) -> Tuple[float, float, float]
7+
def to_dms(value: float, absolute: bool = False) -> Tuple[float, float, float]:
108
"""
119
Split a float value into DMS (degree, minute, second) parts
1210
@@ -24,8 +22,7 @@ def to_dms(value, absolute=False):
2422
return (-degree if invert else degree), minute, second
2523

2624

27-
def to_dm(value, absolute=False):
28-
# type: (float, bool) -> Tuple[float, float]
25+
def to_dm(value: float, absolute: bool = False) -> Tuple[float, float]:
2926
"""
3027
Split a float value into DM (degree, minute) parts
3128
@@ -85,7 +82,7 @@ def __new__(cls, *args):
8582
try:
8683
lat, lng = args
8784
except ValueError:
88-
raise TypeError(f"latlng() takes 2 arguments ({len(args)} given)")
85+
raise TypeError(f"latlng() takes 2 arguments ({len(args)} given)") from None
8986
return tuple.__new__(cls, (latitude(lat), longitude(lng)))
9087

9188
@property
@@ -129,7 +126,7 @@ def z(self):
129126
try:
130127
return self[2]
131128
except IndexError:
132-
raise AttributeError("2D points do not include a z axis.")
129+
raise AttributeError("2D points do not include a z axis.") from None
133130

134131
@property
135132
def is_3d(self):

src/odin/contrib/geo/fields.py

Lines changed: 8 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -22,9 +22,10 @@ def to_python(self, value):
2222
return
2323
try:
2424
return latitude(value)
25+
2526
except (ValueError, TypeError):
2627
msg = self.error_messages["invalid"] % value
27-
raise exceptions.ValidationError(msg)
28+
raise exceptions.ValidationError(msg) from None
2829

2930

3031
class LongitudeField(ScalarField):
@@ -42,9 +43,10 @@ def to_python(self, value):
4243
return
4344
try:
4445
return longitude(value)
46+
4547
except (ValueError, TypeError):
4648
msg = self.error_messages["invalid"] % value
47-
raise exceptions.ValidationError(msg)
49+
raise exceptions.ValidationError(msg) from None
4850

4951

5052
class LatLngField(Field):
@@ -62,9 +64,10 @@ def to_python(self, value):
6264
return
6365
try:
6466
return latlng(value)
67+
6568
except (ValueError, TypeError):
6669
msg = self.error_messages["invalid"] % value
67-
raise exceptions.ValidationError(msg)
70+
raise exceptions.ValidationError(msg) from None
6871

6972

7073
class PointField(Field):
@@ -82,6 +85,7 @@ def to_python(self, value):
8285
return
8386
try:
8487
return point(value)
88+
8589
except (ValueError, TypeError):
8690
msg = self.error_messages["invalid"] % value
87-
raise exceptions.ValidationError(msg)
91+
raise exceptions.ValidationError(msg) from None

0 commit comments

Comments
 (0)