Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Maintain/2 0 remove deprecations #208

Merged
merged 8 commits into from
Feb 5, 2024
2 changes: 1 addition & 1 deletion gemd/__version__.py
Original file line number Diff line number Diff line change
@@ -1 +1 @@
__version__ = "1.18.2"
__version__ = "2.0.0"
4 changes: 2 additions & 2 deletions gemd/demo/cake.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
"""Bake a cake."""
from io import BytesIO
import json
import json as json_builtin
import random

from gemd.entity.attribute import Condition, Parameter, Property, PropertyAndConditions
Expand Down Expand Up @@ -1064,7 +1064,7 @@ def _find_name(name, material):

with open("example_gemd_material_history.json", "w") as f:
context_list = complete_material_history(cake)
f.write(json.dumps(context_list, indent=2))
f.write(json_builtin.dumps(context_list, indent=2))

with open("example_gemd_material_template.json", "w") as f:
f.write(encoder.thin_dumps(cake.template, indent=2))
Expand Down
10 changes: 5 additions & 5 deletions gemd/demo/strehlow_and_cook.py
Original file line number Diff line number Diff line change
Expand Up @@ -46,8 +46,8 @@
def import_table(filename=SMALL_TABLE):
"""Return the deserialized JSON table."""
from importlib.resources import read_text
import json
table = json.loads(read_text("gemd.demo", filename))
import json as json_builtin
table = json_builtin.loads(read_text("gemd.demo", filename))

return table

Expand Down Expand Up @@ -461,7 +461,7 @@ def make_display_table(structured):
Defaults to DEMO_TEMPLATE_SCOPE if none provided.
"""
import os.path
import json
import json as json_builtin
import sys

args = sys.argv[1:]
Expand All @@ -486,11 +486,11 @@ def make_display_table(structured):
break

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

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

print("\n\nCSV -- Display table")
display = make_display_table(full_table)
Expand Down
4 changes: 2 additions & 2 deletions gemd/entity/dict_serializable.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
from abc import ABC, ABCMeta
from logging import getLogger

import json
import json as json_builtin
import inspect
import functools
from typing import TypeVar, Union, Iterable, List, Mapping, Dict, Set, Any
Expand Down Expand Up @@ -122,7 +122,7 @@ def dump(self) -> Dict[str, Any]:
"""
from gemd.json import GEMDJson
encoder = GEMDJson()
return json.loads(encoder.raw_dumps(self))
return json_builtin.loads(encoder.raw_dumps(self))

@staticmethod
def build(d: Mapping[str, Any]) -> DictSerializableType:
Expand Down
15 changes: 2 additions & 13 deletions gemd/entity/link_by_uid.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
"""A unique id that stands in for a data object."""
from typing import TypeVar
import uuid
from warnings import warn

from gemd.entity.dict_serializable import DictSerializable

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

@classmethod
def from_entity(cls, entity: BaseEntityType, name=None, *, scope=None):
def from_entity(cls, entity: BaseEntityType, *, scope=None):
"""
Create LinkByUID from in-memory object.

Expand All @@ -45,8 +44,6 @@ def from_entity(cls, entity: BaseEntityType, name=None, *, scope=None):
----------
entity: BaseEntity
The entity to substitute with a LinkByUID
name: str, optional (Deprecated)
The desired scope of the id.
scope: str, optional
The desired scope of the id.

Expand All @@ -56,16 +53,8 @@ def from_entity(cls, entity: BaseEntityType, name=None, *, scope=None):
A link object that references `entity` through its scope and id.

"""
if name is None and scope is None:
if scope is None:
scope = "auto" # set default
elif name is None and scope is not None: # The rest of these conditions to be deleted
pass # Normal workflow
elif name is not None and scope is None:
warn("The positional argument 'name' is deprecated. When selecting a default scope, "
"use the 'scope' keyword argument.", DeprecationWarning)
scope = name
elif name is not None and scope is not None:
raise ValueError("Specify the 'name' parameter or 'scope' parameter, not both.")

if scope in entity.uids:
uid = entity.uids[scope]
Expand Down
4 changes: 2 additions & 2 deletions gemd/entity/util.py
Original file line number Diff line number Diff line change
Expand Up @@ -116,15 +116,15 @@ def complete_material_history(mat) -> List[Dict[str, Any]]:

"""
from gemd.entity.base_entity import BaseEntity
import json
import json as json_builtin
from gemd.json import dumps, loads
from gemd.util.impl import substitute_links

result = []

def body(obj: BaseEntity):
copy = substitute_links(loads(dumps(obj)))
result.append(json.loads(dumps(copy))["context"][0])
result.append(json_builtin.loads(dumps(copy))["context"][0])

recursive_foreach(mat, body, apply_first=False)

Expand Down
30 changes: 0 additions & 30 deletions gemd/enumeration/base_enumeration.py
Original file line number Diff line number Diff line change
Expand Up @@ -65,36 +65,6 @@ def from_str(cls, val: str, *, exception: bool = False) -> Optional["BaseEnumera
raise ValueError(f"{val} is not a valid {cls}; valid choices are {[x for x in cls]}")
return result

@classmethod
@deprecated(deprecated_in="1.15.0",
removed_in="2.0.0",
details="Enumerations autocast to values now.")
def get_value(cls, name: str) -> str:
"""
Return a valid value associated with name.

If name is equal to one of the enum members, or to the value
associated with an enum member, then return the relevant value.
"""
if name is None:
return None
return cls.from_str(name, exception=True).value

@classmethod
@deprecated(deprecated_in="1.15.0",
removed_in="2.0.0",
details="Use from_str for retrieving the correct Enum object.")
def get_enum(cls, name: str) -> "BaseEnumeration":
"""
Return the enumeration associated with name.

If name is equal to one of the enum members, or to the value
associated with an enum member, then return the relevant enumeration.
"""
if name is None:
return None
return cls.from_str(name, exception=True)

def __str__(self):
"""Return the value of the enumeration object."""
return self.value
Expand Down
32 changes: 0 additions & 32 deletions gemd/json/gemd_json.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
import inspect
from deprecation import deprecated
import json as json_builtin
from typing import Dict, Any, Type

Expand Down Expand Up @@ -213,36 +211,6 @@ def raw_loads(self, json_str, **kwargs):
object_hook=lambda x: self._load_and_index(x, index, clazz_index=clazz_index),
**kwargs)

@deprecated(deprecated_in="1.13.0", removed_in="2.0.0",
details="Classes are now automatically registered when extending BaseEntity")
def register_classes(self, classes):
"""
Register additional classes to the custom deserialization object hook.

This allows for additional DictSerializable subclasses to be registered to the class index
that is used to decode the type strings. Existing keys are overwritten, allowing classes
in the gemd package to be subclassed and overridden in the class index by their
subclass.

Parameters
----------
classes: Dict[str, type]
a dict mapping the type string to the class

"""
if not isinstance(classes, dict):
raise ValueError("Must be given a dict from str -> class")
non_string_keys = [x for x in classes.keys() if not isinstance(x, str)]
if len(non_string_keys) > 0:
raise ValueError(
"The keys must be strings, but got {} as keys".format(non_string_keys))
non_class_values = [x for x in classes.values() if not inspect.isclass(x)]
if len(non_class_values) > 0:
raise ValueError(
"The values must be classes, but got {} as values".format(non_class_values))

self._clazz_index.update(classes)

@staticmethod
def _load_and_index(
d: Dict[str, Any],
Expand Down
11 changes: 0 additions & 11 deletions gemd/util/impl.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@
import functools
from typing import Optional, Union, Type, Iterable, MutableSequence, List, Tuple, Mapping, \
Callable, Any, Reversible, ByteString
from warnings import warn

from gemd.entity.base_entity import BaseEntity
from gemd.entity.dict_serializable import DictSerializable
Expand Down Expand Up @@ -271,7 +270,6 @@ def _make_index(_obj: BaseEntity):
def substitute_links(obj: Any,
scope: Optional[str] = None,
*,
native_uid: str = None,
allow_fallback: bool = True,
inplace: bool = False
):
Expand All @@ -287,21 +285,12 @@ def substitute_links(obj: Any,
target of the operation
scope: Optional[str], optional
preferred scope to use for creating LinkByUID objects (Default: None)
native_uid: str, optional
DEPRECATED; former name for scope argument
allow_fallback: bool, optional
whether to grab another scope/id if chosen scope is missing (Default: True).
inplace: bool, optional
whether to replace objects in place, as opposed to returning a copy (Default: False).

"""
if native_uid is not None:
warn("The keyword argument 'native_uid' is deprecated. When selecting a default scope, "
"use the 'scope' keyword argument.", DeprecationWarning)
if scope is not None:
raise ValueError("Both 'scope' and 'native_uid' keywords passed.")
scope = native_uid

if inplace:
method = _substitute_inplace
else:
Expand Down
10 changes: 5 additions & 5 deletions tests/demo/test_sac.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
"""Test Strehlow & Cook demo."""
from gemd.demo.strehlow_and_cook import make_strehlow_table, make_strehlow_objects, \
minimal_subset, import_table
import gemd.json as je
import json
import gemd.json as gemd_json
import json as json_builtin


def test_sac():
Expand All @@ -12,7 +12,7 @@ def test_sac():

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

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

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

# Verify that the serialization trick for mocking a structured table works
json.dumps(json.loads(je.dumps(sac_tbl))["object"], indent=2)
json_builtin.dumps(json_builtin.loads(gemd_json.dumps(sac_tbl))["object"], indent=2)
4 changes: 2 additions & 2 deletions tests/entity/object/test_material_run.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
"""Test of the material run object."""
import pytest
import json
import json as json_builtin
from uuid import uuid4
from copy import deepcopy

Expand Down Expand Up @@ -33,7 +33,7 @@ def test_material_run():
)

# Make sure that when property is serialized, origin (an enumeration) is serialized as a string
copy_prop = json.loads(dumps(mat_spec))
copy_prop = json_builtin.loads(dumps(mat_spec))
copy_origin = copy_prop["context"][0]["properties"][0]['property']['origin']
assert isinstance(copy_origin, str)

Expand Down
9 changes: 0 additions & 9 deletions tests/entity/test_link_by_uid.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,15 +36,6 @@ def test_from_entity():
link1 = LinkByUID.from_entity(run, scope='foo')
assert (link1.scope, link1.id) == ('foo', 'bar')

with pytest.deprecated_call():
assert LinkByUID.from_entity(run, 'foo').scope == 'foo'

with pytest.deprecated_call():
assert LinkByUID.from_entity(run, name='foo').scope == 'foo'

with pytest.raises(ValueError):
LinkByUID.from_entity(run, name='scope1', scope='scope2')


def test_equality():
"""Test that the __eq__ method performs as expected."""
Expand Down
26 changes: 0 additions & 26 deletions tests/enumeration/test_enumeration.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,32 +8,6 @@
from gemd.json import loads, dumps


def test_values():
"""Test that values can be validated and pulled from an enumeration."""
class GoodClass(BaseEnumeration):
RED = "Red"
BLUE = "Blue"

with pytest.deprecated_call():
assert GoodClass.get_value("Red") == "Red"
with pytest.deprecated_call():
assert GoodClass.get_value(GoodClass.BLUE) == "Blue"
with pytest.deprecated_call():
assert GoodClass.get_value(None) is None
with pytest.deprecated_call():
assert GoodClass.get_enum("Red") == GoodClass.RED
with pytest.deprecated_call():
assert GoodClass.get_enum(GoodClass.BLUE) == GoodClass.BLUE
with pytest.deprecated_call():
assert GoodClass.get_enum(None) is None
with pytest.deprecated_call():
with pytest.raises(ValueError):
GoodClass.get_value("Green")
with pytest.deprecated_call():
with pytest.raises(ValueError):
GoodClass.get_enum("Green")


def test_json_serde():
"""Test that values can be ser/de using our custom json loads/dumps."""
# Enums are only used in the context of another class --
Expand Down
Loading