Skip to content

Commit 6df6538

Browse files
authored
Maintain/2 0 remove deprecations (#208)
* Remove deprecated methods * Annotate json imports for clarity of source
1 parent c80f22e commit 6df6538

File tree

16 files changed

+62
-210
lines changed

16 files changed

+62
-210
lines changed

gemd/__version__.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1 +1 @@
1-
__version__ = "1.18.5"
1+
__version__ = "2.0.0"

gemd/demo/cake.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,5 @@
11
"""Bake a cake."""
22
from io import BytesIO
3-
import json
43
import random
54

65
from gemd.entity.attribute import Condition, Parameter, Property, PropertyAndConditions
@@ -1059,6 +1058,8 @@ def _find_name(name, material):
10591058

10601059

10611060
if __name__ == "__main__":
1061+
import json
1062+
10621063
encoder = GEMDJson()
10631064
cake = make_cake(seed=42)
10641065

gemd/demo/strehlow_and_cook.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -461,7 +461,8 @@ def make_display_table(structured):
461461
Defaults to DEMO_TEMPLATE_SCOPE if none provided.
462462
"""
463463
import os.path
464-
import json
464+
import json as json_builtin
465+
import gemd.json as gemd_json
465466
import sys
466467

467468
args = sys.argv[1:]
@@ -486,11 +487,10 @@ def make_display_table(structured):
486487
break
487488

488489
with open(os.path.join(os.path.dirname(__file__), SMALL_TABLE), 'w') as f:
489-
json.dump(reduced_list, f, indent=2)
490+
json_builtin.dump(reduced_list, f, indent=2)
490491

491492
print("\n\nJSON -- Training table")
492-
import gemd.json as je
493-
print(json.dumps(json.loads(je.dumps(full_table))["object"], indent=2))
493+
print(json_builtin.dumps(json_builtin.loads(gemd_json.dumps(full_table))["object"], indent=2))
494494

495495
print("\n\nCSV -- Display table")
496496
display = make_display_table(full_table)

gemd/entity/dict_serializable.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,6 @@
11
from abc import ABC, ABCMeta
22
from logging import getLogger
33

4-
import json
54
import inspect
65
import functools
76
from typing import TypeVar, Union, Iterable, List, Mapping, Dict, Set, Any
@@ -121,6 +120,8 @@ def dump(self) -> Dict[str, Any]:
121120
122121
"""
123122
from gemd.json import GEMDJson
123+
import json
124+
124125
encoder = GEMDJson()
125126
return json.loads(encoder.raw_dumps(self))
126127

gemd/entity/link_by_uid.py

Lines changed: 2 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,6 @@
11
"""A unique id that stands in for a data object."""
22
from typing import TypeVar
33
import uuid
4-
from warnings import warn
54

65
from gemd.entity.dict_serializable import DictSerializable
76

@@ -31,7 +30,7 @@ def __repr__(self):
3130
return str({"scope": self.scope, "id": self.id})
3231

3332
@classmethod
34-
def from_entity(cls, entity: BaseEntityType, name=None, *, scope=None):
33+
def from_entity(cls, entity: BaseEntityType, *, scope=None):
3534
"""
3635
Create LinkByUID from in-memory object.
3736
@@ -45,8 +44,6 @@ def from_entity(cls, entity: BaseEntityType, name=None, *, scope=None):
4544
----------
4645
entity: BaseEntity
4746
The entity to substitute with a LinkByUID
48-
name: str, optional (Deprecated)
49-
The desired scope of the id.
5047
scope: str, optional
5148
The desired scope of the id.
5249
@@ -56,16 +53,8 @@ def from_entity(cls, entity: BaseEntityType, name=None, *, scope=None):
5653
A link object that references `entity` through its scope and id.
5754
5855
"""
59-
if name is None and scope is None:
56+
if scope is None:
6057
scope = "auto" # set default
61-
elif name is None and scope is not None: # The rest of these conditions to be deleted
62-
pass # Normal workflow
63-
elif name is not None and scope is None:
64-
warn("The positional argument 'name' is deprecated. When selecting a default scope, "
65-
"use the 'scope' keyword argument.", DeprecationWarning)
66-
scope = name
67-
elif name is not None and scope is not None:
68-
raise ValueError("Specify the 'name' parameter or 'scope' parameter, not both.")
6958

7059
if scope in entity.uids:
7160
uid = entity.uids[scope]

gemd/entity/util.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -116,15 +116,15 @@ def complete_material_history(mat) -> List[Dict[str, Any]]:
116116
117117
"""
118118
from gemd.entity.base_entity import BaseEntity
119-
import json
120-
from gemd.json import dumps, loads
119+
import json as json_builtin
120+
import gemd.json as gemd_json
121121
from gemd.util.impl import substitute_links
122122

123123
result = []
124124

125125
def body(obj: BaseEntity):
126-
copy = substitute_links(loads(dumps(obj)))
127-
result.append(json.loads(dumps(copy))["context"][0])
126+
copy = substitute_links(gemd_json.loads(gemd_json.dumps(obj)))
127+
result.append(json_builtin.loads(gemd_json.dumps(copy))["context"][0])
128128

129129
recursive_foreach(mat, body, apply_first=False)
130130

gemd/enumeration/base_enumeration.py

Lines changed: 0 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -65,36 +65,6 @@ def from_str(cls, val: str, *, exception: bool = False) -> Optional["BaseEnumera
6565
raise ValueError(f"{val} is not a valid {cls}; valid choices are {[x for x in cls]}")
6666
return result
6767

68-
@classmethod
69-
@deprecated(deprecated_in="1.15.0",
70-
removed_in="2.0.0",
71-
details="Enumerations autocast to values now.")
72-
def get_value(cls, name: str) -> str:
73-
"""
74-
Return a valid value associated with name.
75-
76-
If name is equal to one of the enum members, or to the value
77-
associated with an enum member, then return the relevant value.
78-
"""
79-
if name is None:
80-
return None
81-
return cls.from_str(name, exception=True).value
82-
83-
@classmethod
84-
@deprecated(deprecated_in="1.15.0",
85-
removed_in="2.0.0",
86-
details="Use from_str for retrieving the correct Enum object.")
87-
def get_enum(cls, name: str) -> "BaseEnumeration":
88-
"""
89-
Return the enumeration associated with name.
90-
91-
If name is equal to one of the enum members, or to the value
92-
associated with an enum member, then return the relevant enumeration.
93-
"""
94-
if name is None:
95-
return None
96-
return cls.from_str(name, exception=True)
97-
9868
def __str__(self):
9969
"""Return the value of the enumeration object."""
10070
return self.value

gemd/json/gemd_json.py

Lines changed: 6 additions & 38 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,4 @@
1-
import inspect
2-
from deprecation import deprecated
3-
import json as json_builtin
1+
import json
42
from typing import Dict, Any, Type
53

64
from gemd.entity.dict_serializable import DictSerializable
@@ -54,7 +52,7 @@ def dumps(self, obj, **kwargs) -> str:
5452
additional = flatten(res, self.scope)
5553
res = substitute_links(res)
5654
res["context"] = additional
57-
return json_builtin.dumps(res, cls=GEMDEncoder, sort_keys=True, **kwargs)
55+
return json.dumps(res, cls=GEMDEncoder, sort_keys=True, **kwargs)
5856

5957
def loads(self, json_str: str, **kwargs):
6058
"""
@@ -79,7 +77,7 @@ def loads(self, json_str: str, **kwargs):
7977
index = {}
8078
clazz_index = DictSerializable.class_mapping
8179
clazz_index.update(self._clazz_index)
82-
raw = json_builtin.loads(
80+
raw = json.loads(
8381
json_str,
8482
object_hook=lambda x: self._load_and_index(x,
8583
index,
@@ -163,7 +161,7 @@ def raw_dumps(self, obj, **kwargs):
163161
A serialized string of `obj`, which could be nested
164162
165163
"""
166-
return json_builtin.dumps(obj, cls=GEMDEncoder, sort_keys=True, **kwargs)
164+
return json.dumps(obj, cls=GEMDEncoder, sort_keys=True, **kwargs)
167165

168166
def thin_dumps(self, obj, **kwargs):
169167
"""
@@ -184,7 +182,7 @@ def thin_dumps(self, obj, **kwargs):
184182
"""
185183
set_uuids(obj, self.scope)
186184
res = substitute_links(obj)
187-
return json_builtin.dumps(res, cls=GEMDEncoder, sort_keys=True, **kwargs)
185+
return json.dumps(res, cls=GEMDEncoder, sort_keys=True, **kwargs)
188186

189187
def raw_loads(self, json_str, **kwargs):
190188
"""
@@ -208,41 +206,11 @@ def raw_loads(self, json_str, **kwargs):
208206
index = {}
209207
clazz_index = DictSerializable.class_mapping
210208
clazz_index.update(self._clazz_index)
211-
return json_builtin.loads(
209+
return json.loads(
212210
json_str,
213211
object_hook=lambda x: self._load_and_index(x, index, clazz_index=clazz_index),
214212
**kwargs)
215213

216-
@deprecated(deprecated_in="1.13.0", removed_in="2.0.0",
217-
details="Classes are now automatically registered when extending BaseEntity")
218-
def register_classes(self, classes):
219-
"""
220-
Register additional classes to the custom deserialization object hook.
221-
222-
This allows for additional DictSerializable subclasses to be registered to the class index
223-
that is used to decode the type strings. Existing keys are overwritten, allowing classes
224-
in the gemd package to be subclassed and overridden in the class index by their
225-
subclass.
226-
227-
Parameters
228-
----------
229-
classes: Dict[str, type]
230-
a dict mapping the type string to the class
231-
232-
"""
233-
if not isinstance(classes, dict):
234-
raise ValueError("Must be given a dict from str -> class")
235-
non_string_keys = [x for x in classes.keys() if not isinstance(x, str)]
236-
if len(non_string_keys) > 0:
237-
raise ValueError(
238-
"The keys must be strings, but got {} as keys".format(non_string_keys))
239-
non_class_values = [x for x in classes.values() if not inspect.isclass(x)]
240-
if len(non_class_values) > 0:
241-
raise ValueError(
242-
"The values must be classes, but got {} as values".format(non_class_values))
243-
244-
self._clazz_index.update(classes)
245-
246214
@staticmethod
247215
def _load_and_index(
248216
d: Dict[str, Any],

gemd/util/impl.py

Lines changed: 0 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,6 @@
33
import functools
44
from typing import Optional, Union, Type, Iterable, MutableSequence, List, Tuple, Mapping, \
55
Callable, Any, Reversible, ByteString
6-
from warnings import warn
76

87
from gemd.entity.base_entity import BaseEntity
98
from gemd.entity.dict_serializable import DictSerializable
@@ -271,7 +270,6 @@ def _make_index(_obj: BaseEntity):
271270
def substitute_links(obj: Any,
272271
scope: Optional[str] = None,
273272
*,
274-
native_uid: str = None,
275273
allow_fallback: bool = True,
276274
inplace: bool = False
277275
):
@@ -287,21 +285,12 @@ def substitute_links(obj: Any,
287285
target of the operation
288286
scope: Optional[str], optional
289287
preferred scope to use for creating LinkByUID objects (Default: None)
290-
native_uid: str, optional
291-
DEPRECATED; former name for scope argument
292288
allow_fallback: bool, optional
293289
whether to grab another scope/id if chosen scope is missing (Default: True).
294290
inplace: bool, optional
295291
whether to replace objects in place, as opposed to returning a copy (Default: False).
296292
297293
"""
298-
if native_uid is not None:
299-
warn("The keyword argument 'native_uid' is deprecated. When selecting a default scope, "
300-
"use the 'scope' keyword argument.", DeprecationWarning)
301-
if scope is not None:
302-
raise ValueError("Both 'scope' and 'native_uid' keywords passed.")
303-
scope = native_uid
304-
305294
if inplace:
306295
method = _substitute_inplace
307296
else:

tests/demo/test_sac.py

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,8 @@
11
"""Test Strehlow & Cook demo."""
22
from gemd.demo.strehlow_and_cook import make_strehlow_table, make_strehlow_objects, \
33
minimal_subset, import_table
4-
import gemd.json as je
5-
import json
4+
import gemd.json as gemd_json
5+
import json as json_builtin
66

77

88
def test_sac():
@@ -12,7 +12,7 @@ def test_sac():
1212

1313
# Check that all shapes of records serialize and deserialize
1414
for comp in sac:
15-
assert je.loads(je.dumps(comp)) == comp
15+
assert gemd_json.loads(gemd_json.dumps(comp)) == comp
1616

1717
# Verify that specs are shared when compounds match
1818
for comp1 in sac:
@@ -27,7 +27,7 @@ def test_sac():
2727

2828
# Make sure there's no migration with repeated serialization
2929
for row in sac_tbl:
30-
assert je.dumps(je.loads(je.dumps(row))) == je.dumps(row)
30+
assert gemd_json.dumps(gemd_json.loads(gemd_json.dumps(row))) == gemd_json.dumps(row)
3131

3232
# Verify that the serialization trick for mocking a structured table works
33-
json.dumps(json.loads(je.dumps(sac_tbl))["object"], indent=2)
33+
json_builtin.dumps(json_builtin.loads(gemd_json.dumps(sac_tbl))["object"], indent=2)

0 commit comments

Comments
 (0)