Skip to content

Commit 4e30ed7

Browse files
committed
Adjust use of TypeVars in Serializable for accuracy and code reuse
Serializable was generic over type T, but that type was only ever used in factory classmethods as a return type, and T was never specified when inheriting from `Serializable[T]`. Instead, we can use a TypeVar only for specifying the return types of the classmethods, which gives us correct type usages and lets us reuse the JSON reading functions within `Serializable`
1 parent 8cb8d9e commit 4e30ed7

1 file changed

Lines changed: 9 additions & 14 deletions

File tree

src/electionguard/serializable.py

Lines changed: 9 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
from dataclasses import dataclass
22
from datetime import datetime
33
from os import path
4-
from typing import Any, cast, Type, TypeVar, Generic
4+
from typing import Any, cast, Type, TypeVar
55

66
from jsons import (
77
dump,
@@ -17,6 +17,7 @@
1717
default_nonetype_deserializer,
1818
)
1919

20+
S = TypeVar("S", bound="Serializable")
2021
T = TypeVar("T")
2122

2223
JSON_FILE_EXTENSION: str = ".json"
@@ -28,7 +29,7 @@
2829

2930

3031
@dataclass
31-
class Serializable(Generic[T]):
32+
class Serializable:
3233
"""
3334
Serializable class with methods to convert to json
3435
"""
@@ -61,35 +62,29 @@ def to_json_file(
6162
write_json_file(self, file_name, file_path, strip_privates)
6263

6364
@classmethod
64-
def from_json(cls, data: str) -> T:
65+
def from_json(cls: Type[S], data: str) -> S:
6566
"""
6667
Deserialize the provided data string into the specified instance
6768
:param data: JSON string
6869
"""
69-
set_deserializers()
70-
return cast(T, loads(data, cls))
70+
return read_json(data, cls)
7171

7272
@classmethod
73-
def from_json_object(cls, data: object) -> T:
73+
def from_json_object(cls: Type[S], data: object) -> S:
7474
"""
7575
Deserialize the provided data object into the specified instance
7676
:param data: JSON object
7777
"""
78-
set_deserializers()
79-
return cast(T, load(data, cls))
78+
return read_json_object(data, cls)
8079

8180
@classmethod
82-
def from_json_file(cls, file_name: str, file_path: str = "") -> T:
81+
def from_json_file(cls: Type[S], file_name: str, file_path: str = "") -> S:
8382
"""
8483
Deserialize the provided file into the specified instance
8584
:param file_name: File name
8685
:param file_path: File path
8786
"""
88-
json_file_path: str = path.join(file_path, file_name + JSON_FILE_EXTENSION)
89-
with open(json_file_path, READ) as json_file:
90-
data = json_file.read()
91-
target = cls.from_json(data)
92-
return target
87+
return read_json_file(cls, file_name, file_path)
9388

9489

9590
def _remove_key(obj: Any, key_to_remove: str) -> Any:

0 commit comments

Comments
 (0)